如何在angularjs中观看数组

时间:2015-03-11 13:00:05

标签: angularjs

尝试观看数组(' CurrentDetails')。但更新后,监视功能内的数据为空。我在哪里错了。

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/

1 个答案:

答案 0 :(得分:2)

触发控制器末尾的init功能。

变量引用的匿名函数将被懒惰地初始化。

有关详细信息check this