Gacha
Gacha

Reputation: 1037

access scope variable from directive by name, avoiding using eval

I'm new to angularJs and the currently working example(fiddle) doesn't feel right. When you try to blur the field it should increment event.times, currently I doing it by $apply on line 10, so I'm asking is there a better way to achieve this ? Maybe something like this var times = scope.$get(attrs.timesField); and then scope.$apply(function(){ times += 1; });

Upvotes: 0

Views: 117

Answers (3)

Mark Rajcok
Mark Rajcok

Reputation: 364697

Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to change the value of that property, use $parse:

<input custom-field times-field="event.times" ng-model="event.title" type="text">

link: function (scope, element, attrs){
   var model = $parse(attrs.timesField);
   element.bind('blur', function(){
       model.assign(scope, model(scope) + 1);
       scope.$apply();
   });
}

fiddle

Upvotes: 3

Derek Ekins
Derek Ekins

Reputation: 11391

There is no need to use eval here, you can just do this:

           scope.$apply(function(){
               scope.event.times++;
           });

However you must ensure that an event object exists on scope before using this directive and I don't think that it is good for a directive to rely on data being set elsewhere.

What are you actually trying to achieve?

Upvotes: 0

Blackhole
Blackhole

Reputation: 20401

You're right, that's not the correct way to do something like that. Find out the $watch() function, especially when using it in directives.

Upvotes: 0

Related Questions