0

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; });

3 Answers 3

3

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

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

Comments

0

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.

1 Comment

With watch I can watch variable for some changes and then do some action, but I don't want to know when the event.times is changed, I want to change it myself.
0

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?

2 Comments

If I do this then there is no point to pass times-field as attribute, I want dynamic attribute.
Yeah you are right, for some reason it didn't click that you were actually passing in the name of the field. That is absoluately the right way to do it and @marks implementation is what you want.

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.