0

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
            });
        }
    };
}])
4
  • account must be undefined before giving it to the directive. How is it initialized? Commented Jun 1, 2016 at 21:11
  • is accounts attached to parent controller scope? $scope.accounts? Commented Jun 1, 2016 at 21:11
  • @RocoCTZ accounts is just a string. it is not attached to any scope Commented Jun 1, 2016 at 21:27
  • That's the problem. It should be. Commented Jun 1, 2016 at 21:31

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.