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>
1

1 Answer 1

0

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

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

Comments

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.