我正在尝试用AngularJS制作一些自定义元素,并将一些事件绑定到它上,然后我注意到$scope.var在绑定函数中使用时不会更新UI。
这里有一个简单的例子来描述这个问题:
HTML:
<!doctype html>
<html ng-app="test">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="Ctrl2">
<span>{{result}}</span>
<br />
<button ng-click="a()">A</button>
<button my-button>B</button>
</div>
</body>
</html>
JS:
function Ctrl2($scope) {
$scope.result = 'Click Button to change this string';
$scope.a = function (e) {
$scope.result = 'A';
}
$scope.b = function (e) {
$scope.result = 'B';
}
}
var mod = angular.module('test', []);
mod.directive('myButton', function () {
return function (scope, element, attrs) {
//change scope.result from here works
//But not in bind functions
//scope.result = 'B';
element.bind('click', scope.b);
}
});
演示:http://plnkr.co/edit/g3S56xez6Q90mjbFogkL?p=preview
基本上,我将click
事件绑定到my-button
,并希望在用户单击按钮B时更改$scope.result
(类似于按钮A上的ng-click:a()
)。但是如果我这样做,视图不会更新到新的$scope.result
。
我做错什么了?谢谢。
发布于 2013-04-18 01:24:14
事件处理程序被称为“外部”Angular,因此尽管您的$scope
属性将会更新,但视图不会更新,因为Angular不知道这些更改。
在事件处理程序的底部调用$scope.$apply()
。这将导致digest cycle运行,并且Angular将注意到您对$scope
所做的更改(由于Angular在您的HTML中使用{{ ... }}
而设置的$watches
)并更新视图。
发布于 2017-09-13 15:58:34
使用超时
$timeout(function () {代码....},0);
https://stackoverflow.com/questions/16066170
复制相似问题