문제

I have some factory:

.factory("someFactory", function() {

  var someFactory = {};

  someFactory.objects = [
    { name: "obj1" },
    { name: "obj2" }
  ];

  return someFactory;
}

And some controller, that watches changes of the names of the objects of this factory:

.controller("someController", ["someFactory", "$scope", function($scope, someFactory) {

  for (var i = someFactory.values.length - 1; i >= 0; i--) {
    $scope.$watch("someFactory.values[" + i + "].name", function(newVal, oldVal, scope) {
        if(newVal !== undefined) {
            // do something
        }
  });

}]);

I was surprised that this actually works and I don't have to write the code for every object in my factory separately. I guess I'm surprised because of my lack of understanding of what $scope.$watch actually does. If someone would ask me, I'd tell him it's like the good ol' observer pattern. Would that be an appropriate explanation?

도움이 되었습니까?

해결책

It's not the observer pattern. With the observer pattern, the observed object explicitely notifies its observers when it changes.

The AngularJS watch mechanism compares the result of the evaluation of the expression before and after an event has been handled, and if the value of the expression has changed, it notifies the watchers. If the watcher execution causes the expression value to be changed again, the watcher is called again, etc. etc. until a limit of 10 cycles has been reached.

This is explained in the $scope documentation.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top