自动刷新.filter()范围

时间:2015-07-06 12:59:30

标签: javascript angularjs angularjs-scope

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

.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示例。

2 个答案:

答案 0 :(得分:2)

过滤器始终首先接收输入值,但您可以在过滤器中传递由:分隔的其他参数。在这种情况下,我已将范围变量编号传递给它。

您不需要$ 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>

答案 1 :(得分:0)

编辑:更新了链接

Does this solve your problem?

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

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