0

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

<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

4

1 回答 1

1

由于您已经隔离了范围,因此您必须使用eiter $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>
于 2013-04-29T17:17:33.447 回答