1

I am trying to trap the first time a model is updated using AngularJS directive. My purpose is to get the initial value of a model to remember in consecutive updates, so if the user changes the initial value I could give some visual indication (add a class) that the value has changed.

I need to have this feature on selected elements so I created a directive vrModify

myApp.directive("vrModify", function () {
return {

    restrict: "A",       
    require:'ngModel',
    link: function(scope, element, attrs, controller) {                                                   


          scope.$watch(attrs.ngModel, function(nVal, oVal){
              //- gets called the first time the model is changed, 
              //- but old and new values are the same.

          });


          element.bind('change', function() {                
              //- not called the first time the model changed.

          });         
    }
}; });

Using $watch did not work as I expected. It gets called when the page is initiated but both old and new values are the same. Using JQuery on change event didn't work either because it doesn't get called when the page is initiated.

Please note I am not trying to capture the change caused by the user but rather the change caused by the model been updated after an Ajax call for example.

Is there a good way to trap the first time a model is initialed (updated) within a directive?

Thanks,

3 Answers 3

1

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.

scope.$watch(attrs.ngModel, function(nVal, oVal){
    if(nVal !== oVal){
        // Do what you want to do here, this time its actually changed for real!
    }
});

source: http://docs.angularjs.org/api/ng.$rootScope.Scope#methods_$watch

3
  • Put that line in but that condition is never true unless the user changes the value on the view. Please note I am not trying to capture the change caused by the user but rather the change caused by the model been updated after an Ajax call for example.
    – DhafirNz
    Dec 18, 2013 at 21:42
  • If this value is never true did you check whether the $watch is being set before or after the value is initialized. The problem might be that the $watch is being set too late. Dec 18, 2013 at 23:26
  • @Dana Shalev - This could be an issue if the model was updated before Angular completed its booting, although I don't know how could that happen. How do I know that Angular has finished booting (scanning) the page an dis ready to process events? Thanks.
    – DhafirNz
    Dec 19, 2013 at 2:09
0

Since we have access to both the previous value (oVal) and the new value (nVal) inside the $watch you can watch when the value changes from it's initial state to something new.

Assuming you're value is initially undefined and as long as nothing resets your value back to undefined, this will set saveThisValue the first time, and only the first time, it's set (and the nVal != undefined will keep this from firing during initialization):

scope.$watch(attrs.ngModel, function(nVal, oVal){
   if ((oVal === undefined) && (nVal != undefined))
     saveThisValue = nval;
}

Here's a demo showing this fires once and only once on the initial change

5
  • Put that line in but that condition is never true unless the user changes the value on the view. Please note I am not trying to capture the change caused by the user but rather the change caused by the model been updated after an Ajax call for example.
    – DhafirNz
    Dec 18, 2013 at 21:43
  • If the value is updated via ajax then you'll probably need to surround that with a $scope.$apply() in order to trigger a $digest- so Angular knows something has changed.
    – KayakDave
    Dec 18, 2013 at 21:46
  • 1
    Yes, or use $http or a wrapper of $http (like ngResource) for your ajax request. Dec 18, 2013 at 21:47
  • I am using $http. The issue is not that at all. I don't need to call $scope.$apply because I am firing my ajax request within Angular context and my view is updated promptly. The issue is that $watch is called when by view is getting updated but both nVal and oVal are the same values. It makes me wonder if both old and new values are the same why the event was triggered at all right from the beginning? I mean if the $watch is for value change, why it was triggered when the value didn't change?
    – DhafirNz
    Dec 19, 2013 at 2:04
  • It's an oddity of startup. But the code I have will ignore that- so I'm puzzled why it didn't fix it. Can you provide an updated fiddle/plunker that shows the problem- to help us volunteers out.
    – KayakDave
    Dec 19, 2013 at 2:13
0

Try using controller.$render function

link: function(scope, element, attrs, controller) {                                                   
        if(!controller) return; 
        controller.$render = function() {
          // this function only gets executed once during the initialisation of the model
        }
          scope.$watch(attrs.ngModel, function(nVal, oVal){
              //- gets called the first time the model is changed, 
              //- but old and new values are the same.

          });


          element.bind('change', function() {                
              //- not called the first time the model changed.

          });         
    }

Another option would be, broadcasting an event when you receive a success response from ajax call and in the directive listen for the event. the syntax would be

// in controller 
$http({
   method:  'GET',
   url: ''
})
.success( 
function(data){
  $scope.$broadcast('modelchanged');
})
.error(
function(error){
});

// in directive

link: function(scope, element, attrs, controller) {
  scope.$on('modelchanged', function(){
    // do what you want to do
  })
}
4
  • This function controller.$render is not getting called at all.
    – DhafirNz
    Dec 22, 2013 at 22:19
  • please use require:'?ngModel' or require:'^ngModel' instead of require:'ngModel'. just to ensure the scope is correct.
    – Kamrul
    Dec 22, 2013 at 23:11
  • Hi Kamrul, still not called at all even with either ? or ^.
    – DhafirNz
    Dec 23, 2013 at 4:25
  • well if this does not work, you can broadcast an event after the success of ajax call and catch the event in the directive. In controller/service where you make the ajax call, use $scope.$broadcast('modelchanged') and in the directive use scope.$on('modelchanged', function(){})
    – Kamrul
    Dec 23, 2013 at 21:20

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.