2015-06-07 50 views
0

我写了这个代码解压到我面临的问题致电服务时,不适用:AngularJS:绑定一个事件

当我直接调用通过NG-点击(“TEST 2 myService() “按钮),myObject.myProperty的值被更新并绑定(视图显示新值)。

但是,当我添加一个事件侦听器(“测试1”按钮),它的值更新,但没有绑定。我可以检查,因为“什么是价值?”当我点击它时突然应用绑定。

然后我真的不明白为什么在事件监听器的情况下这个值没有绑定?

<!DOCTYPE html> 
<html ng-app="testApp"> 
    <head><title>Test</title></head> 
    <body> 

     <section ng-controller="MainController"> 
      {{ myObject.myProperty }} ! 

      <p> 
       <button id="my-button">TEST 1</button> 
       <button ng-click="callMyService()">TEST 2</button> 
      </p> 

      <p><button ng-click="whatIsTheValue()">WHAT IS THE VALUE ?</button></p> 
     </section> 

     <script src="angular.js"></script> 
     <script> 
      var app = angular.module('testApp', []); 

      app.run(function($rootScope, $document, myService) 
      { 
       $rootScope.myObject = { myProperty: 'Run' }; 

       angular.element(document.getElementById('my-button')).bind('click', function(event) 
       { 
        myService(); 
       }); 
      }); 

      app.service('myService', function($rootScope) 
      { 
       return function() 
       { 
        console.log($rootScope.myObject.myProperty); 

        $rootScope.myObject.myProperty = 'Service'; 

        console.log($rootScope.myObject.myProperty); 
       }; 
      }); 

      app.controller('MainController', function($scope, myService, $interval) 
      { 
       $scope.myObject.myProperty = 'Controller'; 

       $scope.callMyService = function() 
       { 
        myService(); 
       }; 

       $scope.whatIsTheValue = function() 
       { 
        console.log($scope.myObject.myProperty); 
       }; 
      }); 
     </script> 

    </body> 
</html> 

回答

1

尝试添加$rootScope.$apply()myService()

angular.element(document.getElementById('my-button')).bind('click', function(event) 
{ 
    myService(); 
    $rootScope.$apply() 
}); 
+0

它完美,谢谢! –

+1

使用'ng-'事件是说角度的方法,请更新相关的'binds',否则你需要明确地使用'$ apply()'来处理它。 – vinayakj

+1

是的。在ng事件中,Angular在默认情况下将其添加到最后,尽管这可能会让你感兴趣:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html –