观察角度变化值之外的变量,然后更新根范围内的角度函数

时间:2014-02-03 22:34:57

标签: angularjs angularjs-scope

我有现有的javascript代码,我需要等到触发才能调用我的角度更新功能。是否可以观察角度控制器外部变量的变化?

            var myoutsidevariable = {};
            // setup angular directives module
            angular.module('scopeInheritance', []).controller('MyListCtrl', function ($scope) {

                // basic initialization here for MyListCtrl controller
                $scope.myList = [{ "Name": "ABC", "KEY": "1" },
                                 { "Name": "DEF", "KEY": "2" },
                                 { "Name": "GHI", "KEY": "3" },
                                 { "Name": "JKL", "KEY": "4" },
                ];

                $scope.update = function (mynames) {
                    $scope.myList = JSON.stringify(mynames);
                };

            }) // now add directive to this 
            .directive('updateMyList', function () {
                $watch(myoutsidevariable, function ($scope) {
                     $scope.update(myoutsidevariable);  // try and update the list items 
               });
            });

            // myoutsidevariable changed... 
            function updatemyoutsidevariable() {
                  myoutsidevariable = 
                                [{ "Name": "XYZ", "KEY": "8" },
                                 { "Name": "VWX", "KEY": "7" },
                                 { "Name": "STU", "KEY": "6" },
                                 { "Name": "PQR", "KEY": "5" },
                                ];        
            }

            updatemyoutsidevariable();

HTML

<div ng-controller="MyListCtrl">
  <ul class="menus">
     <li class="menuitem" ng-repeat="item in myList" value="{{item.KEY}}">{{item.Name}}</li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:0)

它不需要JSON.stringify b / c它已经是一个json对象。