gpt4 book ai didi

javascript - 如何在 Angular JS 中将 Service 中的值公开到 HTML

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

我有一个 AngularJS 服务,我在其中编写了按钮单击功能的逻辑 - 设置 3 秒的超时,以便在单击按钮后显示弹出窗口。

当我在控制台中看到输出时,

$timeout 工作正常。我无法做的是在 ng-if 条件下公开 HTML 模板中的 timeoutFlag

有人可以告诉我这里缺少什么吗?感谢您的帮助!

服务

angular.module('myApp').service('appService', appService);
appService.$inject = ['$rootScope', '$timeout'];

function appService($rootScope, $timeout) {

button = document.getElementById('clickmeBtn');
button.addEventListener('click', function() {

$rootScope.timeoutFlag = true;
console.log('service before timeout - ' + $rootScope.timeoutFlag);
$timeout(function() {
$rootScope.timeoutFlag = false;
console.log('service after timeout - ' + $rootScope.timeoutFlag)
}, 3000)
});
}

Controller

(function() {
angular.module('myApp', []).controller('appController', appController);
appController.$inject = ['$scope', '$rootScope', 'appService'];

function appController($scope, $rootScope, appService) {
var vm = this;
}
})();

HTML

<!doctype html>
<html ng-app="myApp">

<body ng-controller="appController as vm">

<p ng-if="$rootScope.timeoutFlag">Button Clicked</p>

<button id="clickmeBtn">Click me!</button>

<script src="node_modules/angular/angular.min.js"></script>
<script src="scripts/app.controller.js"></script>
<script src="scripts/app.service.js"></script>
</body>

</html>

最佳答案

因为click事件来自AngularJS执行上下文之外,作用域的修改需要通过$apply方法带入AngularJS执行上下文中:

angular.module('myApp').service('appService', appService);
appService.$inject = ['$rootScope', '$timeout'];

function appService($rootScope, $timeout) {

button = document.getElementById('clickmeBtn');
button.addEventListener('click', function() {

$rootScope.$apply(function() {
$rootScope.timeoutFlag = true;
});
console.log('service before timeout - ' + $rootScope.timeoutFlag);
$timeout(function() {
$rootScope.timeoutFlag = false;
console.log('service after timeout - ' + $rootScope.timeoutFlag)
}, 3000)
});
}

只有在 AngularJS 执行上下文中应用的操作才会受益于 AngularJS 数据绑定(bind)、异常处理、属性监视等...

有关详细信息,请参阅AngularJS Developer Guide - Integration with the browser event loop

<小时/>

I'm still not able to display the pop up based on the $rootScope.timeoutFlag value in ng-if condition.

删除 HTML 中对 $rootscope 的引用:

<body ng-controller="appController as vm">

<p ng-if=" ̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶.̶ timeoutFlag">Button Clicked</p>

<button id="clickmeBtn">Click me!</button>

Controller 的作用域从 $rootScope 继承属性。

DEMO on PLNKR

关于javascript - 如何在 Angular JS 中将 Service 中的值公开到 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54833909/

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