0

I have the below code :

variable declaration :

$scope.updateUploadView = 
{
  ready:{
    inview:false,
    text: "starting"
  },
  uploading:{
    inview:false,
    text: "uploading"
  },
  done:{
    inview:false,
    text: "done !"
  }
};

$watch :

angular.forEach($scope.updateUploadView, function(element, key) {
  $scope.$watch(function () {
    return element;
  }, function() {
   // do stuff
  });
},true);
});

The problem here is that i want to ignore $watch to trigger on the undefined property because it cause the view to change 3 times on the start of the application. Is there any possibility to wait the variable declaration ?

http://jsfiddle.net/A8Vgk/2200/

6
  • throw that bunch of code into angular.element(document).ready(function(){ ... }); Commented Feb 4, 2016 at 22:57
  • already tried, still triggers 3 times :( Commented Feb 4, 2016 at 23:04
  • too little information is know about your controller/parent controller/template(s) structure. It's really hard to guess what can possibly affect this. But you have said it has triggered 3 times. that should tell you something! 3 controllers? 3 views? 3 objects? think along those lines. I don't know what else to suggest, find the point where everything is ready before applying watcher Commented Feb 4, 2016 at 23:33
  • i linked a jsfiddle, it'll be easier for you to understand Commented Feb 4, 2016 at 23:36
  • you probably simplified the fiddle example, it seems to be working perfectly fine Commented Feb 4, 2016 at 23:38

1 Answer 1

1

Just check for undefined in your watch function.

$scope.$watch(function () {
  return element;
}, function(newValue, oldValue) {
  if(!angular.isDefined(newValue) && angular.isDefined(oldValue)) {
    // do stuff
  }
});
Sign up to request clarification or add additional context in comments.

6 Comments

Well i was sure it would work but strangly it enter in the condition
Then they must be defined. Check the newValue and oldValue, what are they?
I don't use them ( maybe i'm using totally the wrong method i'm pretty new to angular ) i put a link to a jsfiddle if you want to try it'll be easier for you.
It appears to be working correctly, and since your data is present before you created the $watch, you don't even need to check for undefined as I suggested. It's firing the $watch once for each of the 3 watches you created. If this isn't what you're looking for, try using angular.equals() (see updated answer)
actually, that doesn't work as I expected it to. Check out this post here for suggestions on how to skip the initial $watch stackoverflow.com/questions/16947771/…
|

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.