栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Angular:是否可以监视全局变量(即在范围之外)?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Angular:是否可以监视全局变量(即在范围之外)?

这里的问题可能是您是

myVar
从Angular世界之外进行修改的。Angular不会一直运行摘要周期/脏检查,只有当应触发摘要的应用程序中发生某些事情时,例如Angular知道的DOM事件。因此,即使
myVar
发生了变化,Angular也没有理由开始新的摘要循环,因为什么也没发生(至少Angular知道)。

因此,为了触发您的手表,您需要在更改时强制Angular运行摘要

myVar
。但这有点麻烦,我认为您最好创建一个全局可观察对象,如下所示:

<!doctype html><html ng-app="myApp"><head>    <script src="http://pre.jquery.com/jquery-1.9.1.min.js"></script>    <script src="http://pre.angularjs.org/1.0.5/angular.min.js"></script>    <script>    // Outside of Angular    window.myVar = {prop: "value1"};    var myVarWatch = (function() {        var watches = {};        return { watch: function(callback) {     var id = Math.random().toString();     watches[id] = callback;     // Return a function that removes the listener     return function() {         watches[id] = null;         delete watches[id];     } }, trigger: function() {     for (var k in watches) {         watches[k](window.myVar);     } }        }    })();    setTimeout(function() {        window.myVar.prop = "new value";        myVarWatch.trigger();    }, 1000);    // Inside of Angular    angular.module('myApp', []).controller('Ctrl', function($scope) {        var unbind = myVarWatch.watch(function(newVal) { console.log("the value changed!", newVal);        });        // Unbind the listener when the scope is destroyed        $scope.$on('$destroy', unbind);    });    </script></head><body ng-controller="Ctrl"></body></html>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640670.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号