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>