如果filter在angular指令中,如何过滤数组?

时间:2013-04-29 16:32:17

标签: angularjs angularjs-directive

我尝试创建以角度过滤数组的通用指令。

<body ng-controller="MainCtrl">
    controller: <input type="text" ng-model="query.name" /> - work<br>
    directive: <span filter by="name"></span> - not work
    <ul>
        <li ng-repeat="item in list | filter:query">{{item.name}}</li>
    </ul>
</body>

控制器和指令是:

app.controller('MainCtrl', function($scope) {
    $scope.list = [
        {id: 1, name:'aaa'},
        {id: 2, name:'bbb'},
        {id: 3, name:'ccc'}
    ];
});

app.directive('filter', function () {
    return {
        scope: {
            by: '@'
        },
        link: function postLink(scope, element, attrs) {
            element.append(
                '<input type="text" ng-model="query.' + attrs.by + '">');
        }
    }
});

在控制器中进行过滤,但在指令中过滤不起作用。我不知道如何解决它。

解决方案已在plunker中修复:http://plnkr.co/edit/WLGd6RPQEwMFRBvWslpt?p=preview

1 个答案:

答案 0 :(得分:1)

由于您已经隔离了范围,您必须使用$ parent或者您必须使用'='设置双向绑定我已使用双向绑定更新您的示例

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');</script>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  controller: <input type="text" ng-model="query.name" /> - work<br>
  directive: <span filter by="query"></span> - not work
      <ul>
        <li ng-repeat="item in list | filter:query">{{item.name}}</li>
    </ul>
    <script>
        var app = angular.module('plunker', []);

        app.controller('MainCtrl', function ($scope) {
            $scope.list = [
              { id: 1, name: 'aaa' },
              { id: 2, name: 'bbb' },
              { id: 3, name: 'ccc' }
            ];
            alert("123");
            $scope.query = { name: "" }
        });

        app.directive('filter', function () {
            return {
                scope: {
                    by: '='
                },
                replace: true,
                template:'<input ng-model="by.name"></input>'

            }
        });
    </script>
</body>

</html>