[英]How to rerun filter in Angular
I have this HTML, I cannot change it: 我有这个HTML,我无法更改它:
<div>How much is 100 * X {{100 | myFilter}}</div>
This is the Filter: 这是过滤器:
X=3
app.filter(function(){
return function(val){
return val*X
})
})
Now I want to Change X: 现在我要更改X:
X=5
And I want the HTML to rerun this filter and update all the values that affected by this filter and update the value 我希望HTML重新运行此过滤器并更新受此过滤器影响的所有值并更新该值
X is only defined as global JavaScript var. X仅定义为全局JavaScript变量。 not in the HTML.
不在HTML中。 I want that if the X value changes it will update any filter that depends on it.
我希望如果X值更改,它将更新依赖于它的任何过滤器。
I found an answer. 我找到了答案。 To who else need it.
还有谁需要它。 All what I have to do is to make the filter rerun on every digest cycle::
我要做的就是使过滤器在每个摘要周期中重新运行:
filter.$stateful = true;
Then. 然后。 after changing X, I can simply run the digest cycle using $apply or $digest.
更改X之后,我可以简单地使用$ apply或$ digest运行摘要循环。
JSFiddle that demonstrate stateful filters: JSFiddle演示有状态过滤器:
http://plnkr.co/edit/MRiGzYgXTmLLgrH9FnB1?p=preview http://plnkr.co/edit/MRiGzYgXTmLLgrH9FnB1?p=预览
If I understand you correctly then you want to Change/Input value of X and result should be X * 100 in html. 如果我理解正确,那么您想更改/输入X的值,结果应为html中的X * 100。 Here I have created small demo .
在这里,我创建了一个小演示 。 See if it helps you.
看看是否对您有帮助。
<div ng-app="myApp" ng-controller="MyCtrl">
Input: <input ng-model="X">
<div>How much is 100 * {{X}} = {{X | myFilter}}</div>
</div>
var myApp = angular.module('myApp', []);
myApp.filter('myFilter',function(){
return function(val){
return 100 * val;
}
})
myApp.controller('MyCtrl',['$scope', function($scope) {
$scope.X = 3;
}
]);
Updated demo with stateful filter, external function. 使用状态过滤器和外部功能更新了演示 。
<div id="appid" ng-app="myApp">
<div>How much is 100 * <span id="spX">X</span> {{100 | myFilter}}</div>
</div>
<button onclick="changeX()">
Change
</button>
var X = 3;
var myApp = angular.module('myApp', []);
myApp.filter('myFilter',function(){
function filter(val) {
return val * X;
}
filter.$stateful = true;
return filter;
})
document.getElementById("spX").innerText = X;
function changeX(){
X = 5;
document.getElementById("spX").innerText = X;
var scope = angular.element(document.getElementById("appid")).scope();
scope.$apply();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.