AngularJS Directives: $ scope change not reflected in user interface

I am trying to create some custom elements with AngularJS and bind some events to it, then I noticed that $ scope.var will not update the interface when used in the binding function.

Here is a simplified example describing a task:

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

Basically, I bind the click event to my-button and want to change $scope.result when the user presses button B (similar to ng-click:a() on button A). But if I do so, the view will not be updated to the new $scope.result .

What did I do wrong? Thank.

+52
javascript angularjs
Apr 17 '13 at 17:16
source share
3 answers

Event handlers are called "outside" of Angular, so although your $scope properties will be updated, the view will not be updated because Angular is not aware of these changes.

Call $scope.$apply() at the bottom of the event handler. This will trigger a digest loop, and Angular will notice the changes you made to $scope (due to $watches , which Angular is set to use {{ ... }} in your HTML) and update the view.

+158
Apr 17 '13 at 17:24
source share

It may also be the result of various problems, but with the same symptoms.

If you destroy the parent area assigned to the view, its changes will not affect the view in any way even after calling $apply() . See an example - you can change the value of a view by entering text, but when you click Destroy parent scope! , the model is no longer being updated.

I do not consider this a mistake. This is more likely the result of too hacker code in the application :-)

I ran into this problem when using Angular Bootstrap modal . I tried to open the second modal with the volume of the first. Then I immediately closed the first method, which caused the destruction of the parent area.

+4
Jul 31 '15 at 14:02
source share

use timeout

$ timeout (function () {code ....}, 0);

+1
Sep 13 '17 at 7:58
source share



All Articles