gpt4 book ai didi

javascript - AngularJS : the binding isn't applied when calling a service on an event

转载 作者:行者123 更新时间:2023-12-03 09:57:12 27 4
gpt4 key购买 nike

我编写此代码是为了提取我遇到的问题:

当我通过 ng-click(“TEST 2”按钮)直接调用 myService() 时,myObject.myProperty 的值将被更新并绑定(bind)( View 显示新值)。

但是当我添加事件监听器(“TEST 1”按钮)时,其值会更新但不会绑定(bind)。我可以检查这一点,因为“值(value)是什么?”顺便说一句,当我单击它时,它会突然应用绑定(bind)。

那么我真的不明白为什么在事件监听器的情况下该值没有绑定(bind)?

<!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>

最佳答案

尝试在myService()之后添加$rootScope.$apply()

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

关于javascript - AngularJS : the binding isn't applied when calling a service on an event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30694896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com