0

我试图初始化一个过滤值但没有成功。我将使用 partial/ng-include 所以变量的名称不能改变。

我使用 angularjs v1.0.2,我也尝试使用 v1.1.1

<script>
    function Ctrl($scope) {
      $scope.trains = [ 1, 2];
    }
</script>


<div ng-app ng-controller="Ctrl">
  <div ng-init="t = (trains | filter:1)">    
    {{ t }}
    {{ trains | filter:1 }}
  </div>
  <div ng-init="t = (trains | filter:2)">
    {{ t }}
    {{ trains | filter:2 }}
  </div>
</div>

输出

[2] [1]
[2] [2]

这是这个例子-> http://jsfiddle.net/9q5D4/4/

4

4 回答 4

2

小心使用ng-init表达式(尤其是在初始化新变量时)。在您的示例中,您正在运行 2 个单独的表达式:t = trainsfilter:<X>.

你应该使用t = (trains | filter:<X>)

<div ng-app ng-controller="Ctrl">
  <div ng-init="t = (trains | filter:1)">    
    {{ t }}
    {{ trains | filter:1 }}
  </div>
  <div ng-init="tt = (trains | filter:2)">
    {{ tt }}
    {{ trains | filter:2 }}
  </div>
</div>

jsfiddle:http: //jsfiddle.net/9q5D4/2/

于 2013-01-09T15:56:13.177 回答
1

不确定这是您想要的...但是您可以使用指令来结合 ng-init 和 ng-include:

HTML:

<div ng-app="myApp" ng-controller="Ctrl">    
    <my-directive field-name=1 train=2></my-directive>
    <my-directive field-name=2 train=17></my-directive>
</div>

JS:

function Ctrl($scope, $filter) {
  $scope.trains = [1, 2]; 
}

angular.module("myApp", [])
.directive("myDirective", function() {
    return {
        restrict: "E",
        scope: 'isolate',
        template: "<div>{{exposeAttribute}} {{anotherOne}}</div>",
        controller: Ctrl,
        //templateUrl: "mytemplate.html",
        link: function(scope, element, attr) {
            scope.exposeAttribute = attr.fieldName;
            scope.anotherOne = attr.train;
        }
    };
});

输出是:

1 2

2 17

http://jsfiddle.net/9q5D4/5/

于 2013-05-14T06:23:41.953 回答
0

您是否尝试遍历 $scope.trains?在这种情况下,您应该使用 ng-repeat。我不相信过滤器适用于 ng-init。

http://jsfiddle.net/gtmuh/

<div ng-app ng-controller="Ctrl">
  <div ng-repeat="t in trains | filter:1">
    {{ t }}
    {{ trains | filter:1 }}
  </div>
  <div ng-repeat="t in trains | filter:2">
    {{ t }}
    {{ trains | filter:2 }}
  </div>
于 2013-01-09T15:27:07.300 回答
0

我还没有检查出确切的原因或方式,但似乎在 ng-init 使其工作之前放置了一个 ng-if 属性。

在角度 1.2+ 上测试;

<div ng-app ng-controller="Ctrl">
    <div ng-init="t = (trains | filter:1)">    
        {{ t }}
        {{ trains | filter:1 }}
    </div>
    <div ng-if="true" ng-init="t = (trains | filter:2)">
    {{ t }}
    {{ trains | filter:2 }}
    </div>
</div>
于 2015-07-06T21:16:56.763 回答