AngularJS指令:更改未在UI中反映的$范围

Mar*_* Ni 58 javascript angularjs

我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

演示:http://plnkr.co/edit/g3S56xez6Q90mjbFogkL?p = preview

基本上,我将click事件绑定到用户my-button并且想要$scope.result在用户点击按钮B时更改(类似于ng-click:a()按钮A).但$scope.result如果我这样做,视图将不会更新为新的.

我做错了什么?谢谢.

Mar*_*cok 173

事件处理程序称为"外部"Angular,因此虽然您的$scope属性将更新,但视图不会更新,因为Angular不知道这些更改.

$scope.$apply()在事件处理程序的底部调用.这将导致运行摘要周期,并且Angular将注意到您所做的更改$scope(因为在HTML中$watches使用{{ ... }}了Angular设置)并更新了视图.

  • 很好地解释了,正是我在寻找感谢! (3认同)
  • 我的$ digest已经在进行中,我的视图仅在更新我的范围后响应几秒钟.https://docs.angularjs.org/error/$rootScope/inprog?p0=$digest (3认同)
  • @ ogc-nick,如果你已经处于摘要周期,你不应该调用`$ apply()`.如果您的视图没有更新,那么OP示例中会有不同的内容. (2认同)