自动刷新.filter()作用域



如何更新以下过滤器,有一些方法吗?

.controller('MainCtrl', ["$rootScope", "$scope", function($rootScope, $scope) {
  $rootScope.number = 1;
  $scope.text = "foo|baz|bar"
}]).filter("MyFormat", ["$rootScope", function($rootScope){
  return function(str){
      return str.split("|")[$rootScope.number]
  }
}])
<button ng-click="$root.number = 0">0</button><!--foo-->
<button ng-click="$root.number = 1">1</button><!--baz-->
<button ng-click="$root.number = 2">2</button><!--bar-->
<pre>{{text | MyFormat}}</pre>

这是我的Plunker例子。

过滤器总是首先接收输入值,但您可以在过滤器中传入由:分隔的其他参数。在这种情况下,我已经将您的作用域变量号传递给它

您不需要$rootScope,只需使用控制器作用域即可。此外,当您在html中引用范围变量时,您只使用名称,而不是$scope部分。所以清理后的版本看起来像:

var app = angular.module('MyApp', [])
//Assuming that you do want to use the $rootScope for one reason or another,
//you still access it in the HTML as if it were a scope variable with just
//the name (because it is just a scope variable, it's just one inherited from
//the root).
  .controller('MainCtrl', ["$rootScope", "$scope",
    function($rootScope, $scope) {
      $rootScope.number = 1;
      $scope.text = "foo|baz|bar"
    }
  ])
  .filter("MyFormat", function() {
    return function(str, num) {
      return str.split("|")[num];
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
  <div ng-controller="MainCtrl">
    <button ng-click="number = 0">0</button>
    <!--foo-->
    <button ng-click="number = 1">1</button>
    <!--baz-->
    <button ng-click="number = 2">2</button>
    <!--bar-->
    <pre>{{text | MyFormat : number}}</pre>
  </div>
</div>

编辑:更新链接

这能解决你的问题吗?

我更新了过滤器以获取参数。

  <body ng-controller="MainCtrl">
    <pre>{{text | MyFormat:number}}</pre>
  </body>

最新更新