[英]Use ng-repeat filter in angular directive
I have an directive for repeat my products and it's work fine. 我有一条重复我的产品的指令,并且效果很好。 but i want add some filter add to it.
但我想添加一些过滤器添加到它。
Here is my directive code: 这是我的指令代码:
app.directive('product', ['$compile', function($compile) {
return {
restrict: 'E',
scope: {
products: '='
},
link: function(scope, element, attrs) {
var template =
'<ul>' +
'<li data-ng-repeat="product in products>' +
'{{product.productName}}' +
'</li>' +
'</ul>';
// Render the template.
element.html('').append($compile(template)(scope));
}
}
}]);
When i add directive to my html, show me wired error! 当我将指令添加到html时,向我显示有线错误!
<product products="products | filter:{mainCategoryID : category.categoryID}:true"></product>
error in console: 控制台错误:
How i can fix this issue? 我该如何解决此问题?
try this 尝试这个
var app = angular .module('MyApp', [ ]) .controller('Main', ['$scope', function ($scope) { var self = this; self.products = [{"productName":"a","id":12},{"productName":"b","id":"34"}]; }]) .directive('product', ['$compile', function($compile) { return { restrict: 'E', scope: { products: '=', ngModel : '=', }, link: function(scope, element, attrs) { var template = '<ul>' + '<li data-ng-repeat="product in products |filter:{id:ngModel}">' + '{{product.productName}}' + '</li>' + '</ul>'; // Render the template. element.html('').append($compile(template)(scope)); } } }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div class="main-content" ng-app="MyApp" ng-controller="Main as myCtrl"> <div> <input type="text" ng-model="myCtrl.pID" /> <product products="myCtrl.products " ng-model="myCtrl.pID"></product> </div> </div>
Instead of creating a directive. 而不是创建指令。 Use filter in your
ng-repeat
在
ng-repeat
使用过滤器
<div data-ng-repeat="product in products | filter: checkId"></product>
<ul>
</li>
{{product.productName}}
</li>
</ul>
<div>
In your controller 在您的控制器中
$scope.checkId = #you can do whatever you wanted to.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.