gpt4 book ai didi

javascript - AngularJS:过滤值更改时刷新 DOM

转载 作者:行者123 更新时间:2023-11-28 07:28:45 26 4
gpt4 key购买 nike

我正在尝试创建一个过滤器,当过滤值发生更改时,它可以刷新 HTML 内的 Angular 表达式。所以我基本上在做this :

<!DOCTYPE html>
<html>

<head>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="script.js"></script>
</head>

<body ng-app="GreetingApp" ng-controller="GreetingCtrl">
<p>{{ appName }}</p>
<h1>{{ name | greeting }}</h1>
<br />

Greetword:
<input ng-model="greetWord" />
<button ng-click="GreetingService.setGreetWord(greetWord)">Use "{{ greetWord }}"</button>
<br />
<br />

Name:
<input ng-model="name" />

</body>

</html>

script.js 内部:

angular.module('GreetingApp', [])

.controller('GreetingCtrl', ['$scope', 'GreetingService', '$rootScope', '$timeout',
function($scope, GreetingService, $rootScope, $timeout) {

$scope.appName = 'Greetings!';

$scope.greetWord = 'Hello';

$scope.name = 'World';

$scope.GreetingService = GreetingService;
}])

.service('GreetingService', ['$rootScope', '$q', '$timeout',
function($rootScope, $q, $timeout) {

var service = {

greetWord: 'Hello',

setGreetWord: function(word) {
var deferred = $q.defer();

$rootScope.$applyAsync(angular.bind(this, function() {
this.loadGreetWord(word);
deferred.resolve();
$rootScope.$new;
}));

return deferred.resolve();
},

loadGreetWord: function(word) {
this.greetWord = word;
},

getGreetingFor: function(name) {
return this.greetWord + ' ' + name;
}

};

return service;
}])

.filter('greeting', ['GreetingService',
function(GreetingService) {

return function(name) {
return GreetingService.getGreetingFor(name);
};
}]);

GreetingService.greetWord 的值发生变化时,我想在过滤器中使用它并更新 View 中的文本。但是,当调用 $rootScope.$applyAsync 时,我看不到更改。我的问题出在哪里?

最佳答案

将服务绑定(bind)到 View 是一种不好的做法,您必须避免它。相反,请在 Controller 内执行此操作。

GreetingApp.controller("GreetingCtrl", function($scope, GreetingService) {
$scope.greetWord = GreetingService.greetWord;
$scope.setGreetWord = function(greetWord) {
if(greetWord) {
GreetingService.setGreetWord(greetWord);
}
}
});

在您看来:

当你想使用greetWord来过滤它时,你可以将它设置为过滤器。它将负责过滤:)

  <li ng-repeat="item in names | filter:greetWord">
<greeting name="item.name"></greeting>
</li>

关于javascript - AngularJS:过滤值更改时刷新 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29342895/

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