0

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/

4
  • 2
    There's $watchCollection to watch for changes in the array Commented Mar 11, 2015 at 13:02
  • 1
    try $scope.$watch('CurrentDetails', function (newVal, oldVal) { console.log(newVal); SharedService.updateCurrentDetails(newVal); },true); it should work Commented Mar 11, 2015 at 13:08
  • @pankajparkar; It's empty for both new&old Values Commented Mar 11, 2015 at 13:11
  • @NewDev.Tried with $watchCollection. I see empty [] in the console, still Commented Mar 11, 2015 at 13:11

1 Answer 1

2

trigger the init function at the end of the controller.

Anonymous functions referenced by variables will be initialized lazily.

For more details check this

Sign up to request clarification or add additional context in comments.

5 Comments

Do you have any plnkr/fiddle for this?
Watch is fired with the values, Please have a look at jsfiddle.net/U3pVM/13979
@Vinay.Other than the console.log, could you please tell me the other changes made. I still get empty arrays [] [] in code
declared the module ng-app="myApp" in the markup.
@VinayK +1 Good catch. you played with variables :p

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.