Angular 控制器内的过滤服务

Angular Filter Service inside Controller

首先post永远温柔!!

在 Angular 1.3 中遇到问题并在控制器中使用状态过滤器。

简而言之,当您使用 $filter('custom')(data) 方法作为 {{ data |自定义 }} 方法 - 和自定义过滤器更新(比如服务更新),只有内联( {{ }} )过滤器更新视图。

笨蛋: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);

我已经尝试了很多解决这个问题的方法,包括事件侦听器等,但是这个例子清楚地表明 none 这些方法都有效。

它最初源于使用日期过滤器和动态更新语言环境的语言环境插件,因此当语言环境加载时 - 过滤器没有更新。

欢迎就如何让基于代码的过滤器进行监控(假定某种 $watch 任务)提出任何建议。

提前致谢。

亚当

控制器只执行一次,不是每次范围更新时。 $filter('decorate')($scope.greeting) 在分配给 $scope.code 时进行计算,而 {{greeting | decorate}} 在每次作用域更新时进行计算。 如果您的过滤器未标记为有状态,则过滤器表达式 {{greeting | decorate}} 将仅在 greeting 更新时被评估。 但是 none 这会影响控制器内部的行为。

要在每次 $scope.greeting 更改时更新 $scope.code,您确实可以使用 $scope.$watch:

$scope.$watch('greeting', function(newValue) {
    $scope.code = $filter('decorate')(newValue);
});
    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.

我分叉了一个不使用 $watch 的解决方案,而是一个附加到输入中的 ng-change 的函数,希望对您有所帮助。

  $scope.update = function(){
    $scope.code =$filter('decorate')($scope.greeting);
    };

http://plnkr.co/edit/uPqCz2EpvjNrwCM0ztLs?p=preview