search

Home  >  Q&A  >  body text

angular.js - angular1.x, conflict between dom operation and ng data operation

http://codepen.io/anon/pen/JXogBj?editors=1010

As shown in the above code, if
clicks 1:dom操作 and then clicks 2:ng操作, the value of the label will not change unless you click 3:ng操作 and then click 2:ng操作.
Is there any way to make 2:ng操作 always take effect?

仅有的幸福仅有的幸福2859 days ago810

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-05-15 17:01:06

    Let me explain the reason first

    • 1: DOM operation directly changes the View value, but $scope.name is still 123 and has not changed. This is very important

    • 2: ng operation, because $scope.name is still 123, and it is assigned a value of 123 at this time, it actually does nothing

    • 3: ng operation, $scope.name is assigned a value of 124. At this time, the name changes, and angular goes back to update the value of the view. Because the value is the same, the effect cannot be seen. Then click the 2:ng operation, and $scope.name is assigned a value of 123. If it is changed, the value of the view will be updated synchronously.

    A bit convoluted

    Supplement

    var helloApp = angular.module("helloApp", []);
    helloApp.controller("HelloCtrl", function($scope) {
      $scope.name = "123";  
      
      $('#domopr').click(function(){
        $scope.$apply(function(){
           $scope.name = "124";
        });
      });
    });

    reply
    0
  • Cancelreply