AngularJS指令:改变$scope不反映在UI中
AngularJS Directives: Change $scope not reflected in UI
我试图用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);
}
});
DEMO: http://plnkr.co/edit/g3S56xez6Q90mjbFogkL?p=preview
基本上,我将click
事件绑定到my-button
,并希望在用户单击按钮B时更改$scope.result
(类似于按钮A上的ng-click:a()
)。但是如果我这样做,视图将不会更新到新的$scope.result
。
我做错了什么?谢谢。
事件处理程序是在Angular外部调用的,所以尽管你的$scope
属性会被更新,但视图不会更新,因为Angular不知道这些变化。
$scope.$apply()
。这将导致一个摘要循环运行,Angular会注意到你对$scope
所做的更改(因为在你的HTML中使用了{{ ... }}
,所以Angular设置了$watches
)并更新视图。
这也可能是由于不同的问题,但具有相同的症状。
如果你销毁了父作用域,它的变化不会以任何方式影响视图,即使在$apply()
调用之后。查看示例-您可以通过文本输入更改视图值,但是当您单击破坏父作用域时!,模型不再更新。
我不认为这是一个bug。这是由于应用程序中代码太粗糙所致:-)
我在使用Angular Bootstrap的模态时遇到了这个问题。我试着用第一个模态的范围打开第二个模态。然后,我立即关闭了导致父作用域被销毁的第一个模态。
use timeout
$timeout(function () {代码…},0);
相关文章:
- 具有 UI 引导模式窗口的父$scope子
- AngularJS中存在与$scope变量相关的问题.UI中的值未更改
- 使用ui.grid与cellTemplate共享$scope
- 如何将值与$scope绑定,以从定义状态ui路由器的控制器中使用ng模型进行查看
- 用Angularjs返回两个承诺,How To Chain So UI有$scope
- 设置$scope.parameter,ui路由器
- ui引导Angular模态解析和Scope值
- UI-GRID:访问$scope的问题
- 如何通过角度 ui-grid 中来自$scope的数据动态设置指令
- 使用ui路由器切换状态时保持$scope
- Angular UI Bootstrap Modal Form Scope "undefined"
- 为什么不能从ui-bootstrap模态控制器中绑定$scope字符串值?
- $Scope.$Apply()在加载数据到Angular-Ui-Grid后返回一个圆形错误
- 在angular-ui-grid中,我如何使用rowSelectionChanged与vm而不是$scope
- 如何管理ui-router或在不同的$state中共享$scope
- AngularJS指令:改变$scope不反映在UI中
- Angular UI Router 1.0——为什么在不离开state的情况下调用$scope.$watch('
- 如何在ui-grid中使用$scope变量显示
- UI角度模态控制器$scope值处理错误
- Angular-UI $scope.myMap is undefined