0

I want to make a custom validation directive for my angular app. the only problem is that I dont know how to get an value

<select class="form-control" ng-model="$parent.newSector" ng-options="item.id as item.name for item in sectors" not-empty-array="merchant.sectors"></select>

As you can see from my markup i have got an directive called notEmptyArray where i set an expression (it's the same as ng-model, just a different expression). How can i now access it in my directive?

directive = function({
  require: "ngModel",
  link: function(scope, element, attributes, control) {
    //how to access the value of merchant.sectors (its an array in the scope)
  }
});
2
  • scope.merchant.sectors? Commented Sep 23, 2013 at 13:52
  • yes i could get it this way, but the part of "merchant.sectors" needs to be set by the value of not-empty-array. so if i write users as value of this attribute. it should check for scope.users Commented Sep 23, 2013 at 14:06

1 Answer 1

1

You would need to isolate the scope:

app.directive("notEmptyArray",function(){
    return {
        scope:{
            items:"=notEmptyArray"
        },
        link: function(scope, element, attributes, control) {
            /* anything you feed to "not-empty-array" would be accessible 
              inside items */
            console.log(scope.items);    
        }
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

The downside of isolating the scope is that other directives will no longer work together with your directive if they bind to something from the parent scope (frequent scenario). The reason for this is that a html element can only have one scope. If multiple directives require a scope, only one will be created (the most restrictive one). You will need to do make your directive compatible with other directives be re-exposing some properties on your isolated scope. I suggest you don't go that direction and simply do an : "scope.$eval(attrs.notEmptyArray) to get the value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.