I am new using angularjs and I am trying to create directives. My query is, how can I change the URL of the $http.get from the html. This is my code:
HTML directive:
<form-directive text="Formulario con Directiva" nameinput="true"
namelabel="Nombre:" emailinput="true"
emaillabel="Email:" subjetinput="true" subjetlabel="Asunto:"
message="true" messagelabel="Mensaje:"
dataurl="URL to change">
</form-directive>
JS:
<script>
angular.module('testDirective', [])
.controller('testDir', function ($scope, $http) {
$scope.textoFalopa = "Hola, es una prueba";
})
.directive('formDirective', function () {
return {
restrict: "EA",
templateUrl: './template.html',
scope: {
text: '@',
nameinput: '=nameinput',
namelabel: '@',
emailinput: '=emailinput',
emaillabel: '@',
subjetinput: '=subjetinput',
subjetlabel: '@',
message: '=message',
messagelabel: '@',
dataurl:'='
},
controller: ['$scope', '$http', function ($scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/users').then(function (remotedata) {
console.log(remotedata.data);
$scope.data = remotedata.data;
});
}],
link: function (scope) {
console.log(scope);
}
};
});
</script>
Thank you!
I'm assuming what you are looking to do is to get the value of the attribute on your directive declaration
dataurl="URL to change"and use that as the URL in the $http call.The properties in the
scopeobject define the bindings of these attributes to your AngularJS scope (injected as$scope).You have already bound
dataurlto your scope, so you're half way there. Now the the most straightforward way of getting the in the example you have posted would be to just use the$scopeobject in your controller. Like so:Be advised that best practice with AngularJS is now to only use
$scopedirectly when needing it's advanced features. For this kind of simple case you shouldn't need to inject it. I would suggest looking into AngularJS components and/or thebindToControllerproperty.An alternative (but perhaps messy) solution if you just want to get the attribute is to inject
$elementwhich gives you access to the underlying jQuery object.Though this isn't really the 'angular way' so I'd only use it for quick hacks or messy workarounds.
So you have three approaches there. Any one will work, but I would suggest learning components and controller binding as that will encourage good practice and put you in good stead for learning Angular 2+