sukesh
sukesh

Reputation: 2437

how to watch an array in angularjs

Trying to watch an array ('CurrentDetails'). But the data is empty inside the watch function, after updating it. where am i going wrong here.

myctrl.js:

 app.controller("myctrl", function ($scope, SharedService) {
       $scope.CurrentDetails = [];

      var init = function(){
      var data = {
                OptionsType: "LanguageOptions",
                OptionItems: [{ "OptionId": 1, "OptionName": "English"}],
                Breadcrumbs: ["Home"]
            }                
            $scope.ShowResponse(data);
     }
     $scope.ShowResponse = function (data) {
        $scope.CurrentDetails = data;  
        console.log($scope.CurrentDetails); //can see the data here
     }

       $scope.$watch('CurrentDetails', function () {
        console.log($scope.CurrentDetails); //no data here 
        SharedService.updateCurrentDetails($scope.CurrentDetails);
      },true);
       $scope.$on('valuesUpdated', function () {        
          $scope.CurrentDetails = SharedService.CurrentDetails;        
      });

       init();
    }

sharedservice.js:

app.service("SharedService", ['$rootScope', function ($rootScope) {
 var service = {};
 service.CurrentDetails = [];
 service.updateCurrentDetails = function (value) {
        this.CurrentDetails = value;
        $rootScope.$broadcast("valuesUpdated");
    }

}]);

http://jsfiddle.net/U3pVM/13977/

Upvotes: 0

Views: 47

Answers (1)

Vinay K
Vinay K

Reputation: 5572

trigger the init function at the end of the controller.

Anonymous functions referenced by variables will be initialized lazily.

For more details check this

Upvotes: 2

Related Questions