nosthertus nosthertus - 6 months ago 51
AngularJS Question

Angularjs: custom directive scope is undefined

I am creating a directive that process data from attribute value. the directive is only going to be used as an attribute on an element. So for now i just want to run a function whenever it is called

The directive call is like this:

<div rest="accounts">
{{testing}}
</div>


Directive definition goes like this:

app.directive("rest", [function(){
return {
restrict: 'A',
scope: {
rest: '='
},
link: function(scope, element, attrs, ctrl) {
console.log(scope);
}
};
}])


everytime i use the directive, the log shows the property
rest
as
undefined
.. accounts is just a string because i want to test the directive first, but yet i don't know why it is always undefined, even with using
$watch
like this:

app.directive("rest", [function(){
return {
restrict: 'A',
scope: {
rest: '='
},
link: function(scope, element, attrs, ctrl) {
scope.$watch('rest', function(data){
console.log(data); //Still undefined
});
}
};
}])

Answer

The method you are using to pass values is passing a variable reference rather than a string value.

With rest="accounts" in the HTML, = in scope implies two way binding, where the inner property scope.rest is bound to the outer property $scope.accounts.

If you always intend to pass a string, you should use @ in the scope property instead. This implies a one way binding between rest and the string value.

You can also use the directive as written without defining $scope.accounts by supplying your value as a string literal, i.e. rest="'accounts'". This form should be used sparingly, however, due to the cumbersome nature of the nested quotes.