AngularJS指令:更改$范围没有反映在UI [英] AngularJS Directives: Change $scope not reflected in UI

查看:176
本文介绍了AngularJS指令:更改$范围没有反映在UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让与AngularJS的一些自定义的元素和一些事件绑定到它,然后我注意到在绑定功能使用时,$ scope.var不会更新UI。

I'm trying to making some custom elements with AngularJS's and bind some events to it, then I notice $scope.var won't update UI when used in a binding function.

下面是一个简单的例子,说明万阿英,蒋达清:

Here is a simplified example that describing the probelm:

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:<一href=\"http://plnkr.co/edit/g3S56xez6Q90mjbFogkL?p=$p$pview\">http://plnkr.co/edit/g3S56xez6Q90mjbFogkL?p=$p$pview

基本上,我绑定点击事件我的按钮并要更改 $ scope.result 当用户点击按钮B(类似于 NG-点击:一个()按钮A)。但视图不会更新到新的 $ scope.result 如果我这样做的方法。

Basicly, I bind click event to my-button and want to change $scope.result when user clicked button B (similar to ng-click:a() on button A). But the view won't update to the new $scope.result if I do this way.

我做了什么错?谢谢你。

What did I do wrong? Thanks.

推荐答案

事件处理程序被称为外的角,所以虽然你的 $范围属性将被更新时,视图将不会更新,因为角度不知道这些变化。

Event handlers are called "outside" Angular, so although your $scope properties will be updated, the view will not update because Angular doesn't know about these changes.

呼叫 $范围。$适用()在事件处理程序的底部。这将导致一个消化周期来运行,角会注意到你的 $范围(因为 $手表的角度设置由于使用 {{...}} 在你的HTML),并更新视图。

Call $scope.$apply() at the bottom of your event handler. This will cause a digest cycle to run, and Angular will notice the changes you made to the $scope (because of the $watches that Angular set up due to using {{ ... }} in your HTML) and update the view.

这篇关于AngularJS指令:更改$范围没有反映在UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆