【发布时间】:2016-05-18 21:16:01
【问题描述】:
我在几个视图上使用元素指令。该指令对资源列表中的每个“资源”重复,就像这样:ng-repeat="resource in resources"。
不同的页面控制器将通过在每个视图控制器中使用不同的 $scope.resourceApiPath 来确定将从 API 中提取哪些资源,然后指令控制器使用该 $http 调用。
这适用于显示不同资源的不同视图。比如一个视图显示所有用户自己的资源,一个视图显示公共资源,一个视图显示用户已加星标的资源等。
唯一的问题是,对于我的一个观点,我想在ng-repeat 上添加一个过滤器,如下所示:ng-repeat="resource in resources | filter:resourceSearch.text"。有没有办法让我根据条件添加这个过滤器,例如如果是$scope.filter == true;,否则只返回常规的ng-repeat="resource in resources"?
这是我的指令:
.directive('resourcePanel', function() {
return {
restrict: 'E',
scope: false,
templateUrl: 'scripts/templates/resource-panel.html',
controller: 'ResourcesPanelController'
}
})
指令中引用的ResourcesPanelController 是这样的:
$scope.resources = [];
$scope.loadResources = function() {
$scope.resources = []; // Empty the array
$http.get('/api/resource' + $scope.resourceApiPath)
.then(function(res) {
$scope.resources = res.data.message;
});
};
$scope.loadResources();
scripts/templates/resource-panel.html 元素模板如下所示:
<div class="panel" ng-repeat="resource in resources">
{{resource.content}}
</div>
谢谢!
【问题讨论】:
标签: javascript angularjs angularjs-directive angular-controller