第一篇文章,所以要温柔!!
在Angular 1.3中出现问题,并在控制器中使用状态过滤器。
简而言之,当您使用$ filter('custom')(data)方法作为{{data | custom}}方法 - 以及cutom过滤器更新(比如服务更新),只有内联({{}})过滤器更新视图。
Plunkr:http://plnkr.co/edit/nukioL3ORnl9KDPHmNoY?p=preview
(function(angular) {
'use strict';
angular.module('myStatefulFilterApp', [])
.filter('decorate', ['decoration',
function(decoration) {
function decorateFilter(input) {
return decoration.symbol + input + decoration.symbol;
}
decorateFilter.$stateful = true;
return decorateFilter;
}
])
.controller('MyController', function($filter, $scope, decoration) {
$scope.greeting = 'hello';
// This will update
$scope.decoration = decoration;
// This won't
$scope.code = $filter('decorate')($scope.greeting);
})
.value('decoration', {
symbol: '*'
});
})(window.angular);
我已经尝试了许多这个问题的解决方案,涉及事件监听器等,但是这个例子清楚地表明这些都不会起作用。
它最初源于使用日期过滤器和动态更新语言环境的语言环境插件,因此当语言环境加载时 - 过滤器不会更新。
欢迎任何关于如何让基于代码的过滤器进行监控的建议(假定某种类型的$ watch任务)。
提前致谢。
亚当
答案 0 :(得分:3)
控制器只执行一次,而不是每次更新示波器。 $filter('decorate')($scope.greeting)
在分配给$scope.code
时会被评估,而{{greeting | decorate}}
会在每次更新范围时进行评估。
如果您的过滤器未标记为有状态,则仅在{{greeting | decorate}}
更新时才会评估过滤器表达式greeting
。
但这些都不会影响控制器内部的行为。
要在每次$scope.code
更改时更新$scope.greeting
,您确实可以使用$scope.$watch
:
$scope.$watch('greeting', function(newValue) {
$scope.code = $filter('decorate')(newValue);
});
答案 1 :(得分:1)
I think you should try to use $watch.
It will resolve the problem.
Here is the updated script.
http://plnkr.co/edit/4IlBIhh2JfmPcMDW0ty6?p=preview
Hope this will help you.
Thanks.
答案 2 :(得分:0)
我分解了一个不使用$ watch的解决方案,但输入中附加了ng-change的函数,希望有所帮助。
$scope.update = function(){
$scope.code =$filter('decorate')($scope.greeting);
};