我无法弄清楚为什么ng-options指令在我的例子中不起作用:
http://plnkr.co/edit/wwAIDHl6U7YaScRzIKAY
app.coffee
app = angular.module('plunker', [])
app.controller 'MainCtrl', ($scope) ->
$scope.query = {}
$scope.types = ["Test", "Demo", "Numeric", "ABC"]
$scope.items = [{typ: "Test"},{typ: "Test"},{typ: "Demo"}, {typ: "Numeric"}]
app.directive 'colFilterable', ($parse) ->
{
restrict: 'A',
scope: {
colFilterable: '=',
filterableKey: '@',
filterableOptions: '='
filterableOptionsArg: '@',
},
compile: (el, $scope) ->
if $scope.filterableKey
key = $scope.filterableKey
else
key = el.text().toLowerCase()
options = 'label for value in filterableOptions'
if $scope.filterableOptionsArg
options = $scope.filterableOptionsArg
el.append('<select class="col-filterable" ng-model="filter" ng-options="' + options + '"><option></option></select>')
return ($scope, el, attrs) ->
$scope.$watch 'filter', () ->
$scope.colFilterable[key] = $scope.filter
}
的index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h2>DEMO</h2>
<table>
<thead>
<tr>
<th col-filterable="query" filterable-options="types">
Typ
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items | filter: query">
<td>{{item.typ}}
</tr>
</tbody>
</table>
<h2>DEBUG</h2>
<p>{{ types }}</p>
<p>{{ query }}</p>
</body>
</html>
我在编译函数中附加带有ng-options的选项(可以传入,但默认为label for value in filterableOptions
)并返回一个链接函数,该函数监视ng-model并设置数据绑定$scope.colFilterable
到$scope.filter
我无法使用模板,因为我想保留当前元素内部的内容,只想附加这个选择,而这反过来应该过滤生成的表
编辑:
好的,似乎$scope.$watch 'filter'
不会以任何方式工作,结果也不会传播到父作用域,所以我重新编写它以使用更改事件
http://plnkr.co/edit/qzaf1sBoFuVD8fow0tfA
el.find('select').bind 'change', (event) ->
$scope.colFilterable[key] = this.value
$scope.$apply()
如果我手动编写option
元素
答案 0 :(得分:0)
好吧,我通过使用模板和链接函数而不是编译函数来解决这个问题。 这是我现在的解决方案
app.directive 'colFilterable', ($parse) ->
{
restrict: 'A',
scope: {
colFilterable: '=',
filterableKey: '@',
filterableOptions: '='
filterableOptionsArg: '@',
},
template: (el, attr) ->
options = 'value as value for value in filterableOptions'
if attr.filterableOptionsArg
options = attr.filterableOptionsArg
return el.html() + '<select class="col-filterable" ng-model="filter" ng-options="' + options + '"><option value="">Alle</option></select>'
link: ($scope, el, attr) ->
if attr.filterableKey
key = attr.filterableKey
else
key = el.text().toLowerCase().trim()
el.find('select').bind 'change', (event) ->
if $scope.filter
$scope.colFilterable[key] = $scope.filter
else
delete $scope.colFilterable[key]
$scope.$apply()
}