0

I am new to Angular, but i do not understand why controller updates data from service only in some cases ... http://plnkr.co/edit/pV8m11Bc1vItDSmQKECS?p=preview object1 and 2 are correctly updated, but objet3 is not. Seems that Service.get3() is just fired once. I understand that Angular watch for object changes, fine for object1 and object2 (that is a reference to object1) by the way, it's great. But it's not working with object3 ... ok it's not a reference... The question is : how to build new objects in service ?

Thank you, Philippe

var app = angular.module('App', []);

app.factory('Service', [

  function() {
    var object1 = ["TOTO"];
    return {
      get1: function() {
        return object1;
      },
      get2: function() {
        var object2 = object1;
        return object2;
      },
      get3: function() {
        var object3 = [];
        /*
                object1.forEach(function(entry) {
                    object3.push(entry);
                    console.log(entry);
                });
                */

        for (i = 0; i < object1.length; i++) {
          object3.push(object1[i]);
        }

        return object3;
      },
      set: function(newValue) {
        object1.push(newValue);
      }
    }
  }
]);

app.controller('Controller', ['$rootScope', '$scope', 'Service',
  function($rootScope, $scope, Service) {

    $scope.object1 = Service.get1();
    $scope.object2 = Service.get2();
    $scope.object3 = Service.get3();

    $scope.set = function() {
      Service.set("TITI");
    }
  }
]);

2 Answers 2

1

As mentioned the third object is a different array. In order to have it notify your controller of changes you'll probably want to register a watch on it:

http://plnkr.co/edit/EdXVKqe5eaZgROFDG9U9?p=preview

$scope.$watch(Service.get3, function(val) {
   $scope.object3 = Service.get3();
    });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. $watch from controllers to see updates from services is a workaround or is the right way to share new data ? I know the best is to shared references, but it's not always possible.
Watches are an integral part of angular.
0

The first two are bound to object1. The third is bound to a different array altogether.

Comments

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.