我写了这段代码来解决我遇到的问题:
当我通过ng-click(“TEST 2”按钮)直接呼叫myService()
时,myObject.myProperty
的值会更新并绑定(视图显示新值)。
但是当我添加一个事件监听器(“TEST 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>
答案 0 :(得分:1)
尝试在$rootScope.$apply()
myService()
angular.element(document.getElementById('my-button')).bind('click', function(event)
{
myService();
$rootScope.$apply()
});