I’m trying to create a directive, where I need some additional details which has to be passed as attributes for the elements.
These values are of static nature. ie: there won’t be any scoped reference in the parent scope (It is a boolean value)
In the directives link function I need these attributes to be accessible in the link function of the directive, but the value is coming as undefined.
Mark up:
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<div my-directive local-attr="attribute" local-ref="ref">
</div>
</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function(){
return {
scope: {
localAttr:'@',
localRef:'='
},
link: function(scope, iElement, iAttrs, controller) {
console.log(scope.localAttr, scope.localRef);
}
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
$scope.ref="reg"
}]);
In this demo, I need to get the value attribute for scope.localAttr in the link function.
Demo: Fiddle
If value is 100% static, you can use
iAttrs.localAttr(and you can skip bind inscope: {..})if value should be interpolated (there is
{{...}}) you should useiAttrs.$observe('localAttr', cb)(and also you can skip mentioning it inscope: {...})If you would like to do some manipulations with other scope properties, you should
$scope.watch('localAttr', cb).It could be even expected that during linking scope could be not fully constructed. In AngularJS documentation about ‘scope’ parameter of link function there is
http://docs.angularjs.org/guide/directive
So generally you can only register watchers, and not get values.