0

I have existing javascript code I need to wait to fire before calling my angular update function. Is it possible to observe changes to a variable outside an angular controller?

            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>
user3250966
  • 139
  • 1
  • 13
  • 1
    possible duplicate of [AngularJs watch window variable](http://stackoverflow.com/questions/20667012/angularjs-watch-window-variable) – Stewie Feb 03 '14 at 22:47

1 Answers1

0

It doesn't need JSON.stringify b/c its already a json object.

user3250966
  • 139
  • 1
  • 13