我仅将Angular用作模块以在无序列表中显示数组的内容。
我的代码如下:
// script.js - plain JS:
let array = []
element.addEventListener('click',function append(){
array.push(someValue);
})
// ng-app and ng-controller are set only on UL element,
// click listener is set on other element outside of ng-app's / controller's scope, array is window's global variable
// in angular app.js controller - this doesn't work:
$scope.$watch(()=>return $window.array.length,
(oldVal, newVal)=>{
console.log(oldVal, newVal );
$scope.array = $window.array
})
$手表在鼠标单击更新阵列时无能为力,只有在窗口加载时才可以做什么。
它不起作用,因为$scope.$watch
与$digest
循环关联,因此您应该在事件机制的帮助下进行人工启动:$rootScope.$broadcast
和$scope.$on
(而不是$scope.$watch
):
let array = []
function register($rootScope, element) {
element.addEventListener('click', function append() {
array.push(array.length + 1);
$rootScope.$broadcast('customEvent', array.length);
})
}
angular.module('app', [])
.run(function($rootScope) {
register($rootScope, document.getElementById('test'));
})
.controller('ctrl', function($scope) {
$scope.logs = [];
$scope.$on('customEvent', function(event, data) {
$scope.$apply(function() {
$scope.logs.push(data);
});
})
})
h4{
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div ng-app='app' ng-controller='ctrl'>
<h4 id='test'>Click ME</h4>
<ul ng-if='logs.length > 0'>
<li ng-repeat='log in logs'>{{log}}</li>
</ul>
</div>