【发布时间】:2016-11-24 13:14:39
【问题描述】:
在 Angular (v1.3) 中,如何将变量从 ng-repeat 绑定到自定义指令?
所有示例似乎都绑定到 $scope 变量。例如,给定一个产品列表和一个名为 product 的自定义指令,我们如何才能做到这一点:
<li ng-repeat="product in products">
<product item="product" />
</li>
指令的创建位置:
(function () {
'use strict';
var productDirective = function () {
return {
restrict: 'E',
scope: {item: '='},
templateUrl: '/views/product.html',
};
};
angular
.module('myApp')
.directive('product', productDirective);
})();
它有一个非常简单的模板:
<p>{{item.name}} {{item.price}}</p>
这失败了,因为 scope: '=' 只绑定到 $scope,而不绑定到 ng-repeat。
我能够让它与它一起工作
return {
restrict: 'E',
scope: {item: '@'},
templateUrl: '/views/product.html',
link: function(scope, element, attributes){
scope.item = scope.$eval(attributes.item);
}
};
但是 $eval 的使用当然是不可接受的(不好的风格)。
实现此目的的正确角度方式是什么?
【问题讨论】:
标签: angularjs angularjs-directive angularjs-ng-repeat