javascript - Why does an externally updated array not automatically refresh? -


i have js class handles logic, , trying use in angular can automatically update when value changes not work, when use angular functions works , reference ok, sure need else tell angular need listen when array changes externally. thanks!

http://jsfiddle.net/9k2zw1ar/

//create class exposed window (function(w){      var foo=function(){         this.add=function(){             foo.arr.push('js-'+(math.random() * 100));         }     }     foo.arr=['a','b','c'];     w.foo=foo; })(window); //instantiate 1 class , used in button var foo=new foo; //angular app var app= angular.module('app',[]); //add array reference using "value"  app.value('arr',foo.arr); //angular controller app.controller('clientcontroller', ['$scope','arr', function($scope,arr) {   $scope.markers = arr;   $scope.add=function(){     arr.push('ng-'+(math.random() * 100));   }; }]); 

here html code

<div ng-app="app" >  <div ng-controller="clientcontroller">    <div  ng-repeat='marker in markers'>               <p> {{marker}}</p>    </div>     <button ng-click='add()'>add ng</button>     <button  onclick="foo.add()">add js</button> </div>  </div> 

problem: when change array button "add js" not update automatically. when press "add ng" button array shown , updated right away.

the problem when change array outside of angular app, doesn't know has changed. need notify it, scope needs update watchers. need trigger digest loop manually, example calling $apply method on root scope.

the tricky part need access scope somehow outside. access root scope of application need call scope method of angular.element(approot) element. approot dom element on application registered (ng-app attribute). example this:

var foo = function () {     this.add = function () {         foo.arr.push('js-' + (math.random() * 100));         this.apply();     };      this.apply = function() {         var approot = document.queryselector('[ng-app]');         angular.element(approot).scope().$apply();     }; } 

demo: http://jsfiddle.net/9k2zw1ar/1/


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -