AngularJS - $ scope mechanics. Is $ Watch just an observer pattern?

I have a factory:

.factory("someFactory", function() {

  var someFactory = {};

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

  return someFactory;
}

And some kind of controller that monitors changes to the names of 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 really works, and I do not need to write code for each object in my factory separately. I guess I'm surprised that I don’t understand what $ scope is. If someone asks me, I will tell him that this is a good example of an observer. Would this be a suitable explanation?

+4
source share
1 answer

This is not an observer pattern. When using the observer pattern, the observed object explicitly notifies its observers when it changes.

AngularJS , , . , .. .. 10 .

$scope documentation.

+6

Source: https://habr.com/ru/post/1530703/


All Articles