This is my app config:
angular.module('myApp', ['myApp.directives', 'myApp.controllers', 'myApp.services']);
This is my controller:
angular.module('myApp.controllers', [])
.controller('MainCtrl', function ($scope) {
$scope.name = 'world';
});
This is my directive:
var directives = angular.module('myApp.directives', []);
directives.directive("hello", function () {
return function (scope, elm, attrs) {
elm.text("hello, " + scope[attrs.name]);
};
});
and this is my html:
<div ng-controller="MainCtrl">
<h1 hello></h1>
</div>
The is problem is that angular render the directive as:
hello, undefined
Instead of:
hello, world
What is wrong?
You are accessing scope[attrs.name]
but the directive doesn't provide a value for the attribute name
There are 2 options:
Change the directive to elm.text("hello, " + scope['name']);
This is not a preferred way as it hard codes to a scope property name
Change the html to <h1 hello name="name"></h1>
. This is better but I feel it uses a redundant attribute
I would suggest you change the directive to elm.text("hello, " + scope[attrs['hello']]);
Or even better elm.text("hello, " + scope.$eval(attrs['hello']));
this way you get the benefit of expressions as well(ex: <h1 hello="name|uppercase"></h1>
)
demo
This way the html would be <h1 hello="name"></h1>
Regarding the attrs parameter: it's nothing more than a map of strings taken from the attributes present on the dom element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With