AngularJS 指令:更改 $scope 未反映在 UI 中

2024-01-19

我正在尝试使用 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 http://plnkr.co/edit/g3S56xez6Q90mjbFogkL?p=preview

基本上,我债券click事件至my-button并想要改变$scope.result当用户单击按钮 B 时(类似于ng-click:a()按钮 A)。但视图不会更新为新的$scope.result如果我这样做的话。

我做错了什么?谢谢。


事件处理程序被称为“外部”Angular,因此尽管您的$scope属性将被更新,视图将不会更新,因为 Angular 不知道这些更改。

Call $scope.$apply()在事件处理程序的底部。这将导致消化循环 http://docs.angularjs.org/guide/concepts#runtime运行,Angular 会注意到您对$scope(因为$watchesAngular 由于使用而设置{{ ... }}在您的 HTML 中)并更新视图。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AngularJS 指令:更改 $scope 未反映在 UI 中 的相关文章

随机推荐