In this plunk我有一个带有嵌套元素列表的指令(“值0”,“值1”等)。我需要的是将这个列表放在一个指令变量中(参见范围列表)。我试过transclude
,但无法理解。有什么想法吗?
HTML
<directive>
<ul>
<li id="0">Value 0</li>
<li id="1">Value 1</li>
<li id="2">Value 2</li>
</ul>
</directive>
的Javascript
angular.module('app', []);
angular.module('app')
.directive('directive', function() {
var directive = {};
directive.restrict = 'AE';
directive.scope = true;
directive.template = "<div>{{list}}</div>";
directive.link = function(scope, element, attrs) {
// This is how scope.list should end up
// scope.list = [ {id:0, name:"Value 0"},
// {id:1, name:"Value 1"},
// {id:2, name:"Value 2"} ];
};
return directive;
});
答案 0 :(得分:0)
回答更新v2
我认为这就是你想要的,在这个例子中我们创建了一个从控制器绑定数组的指令。
var app = angular.module('app', []);
app.controller("ctrl", function ($scope) {
$scope.array = [
{name: "Value 0"},
{name: "Value 1"},
{name: "Value 2"}
]
})
app.directive("directive", function () {
return {
restrict: "E",
transclude: true,
template: "<div ng-transclude></div>",
link: function (scope, element) {
console.log(scope.array)
}
};
});
<!DOCTYPE html>
<html ng-app="app" ng-controller="ctrl">
<head>
<meta charset="utf-8" />
</head>
<body>
<directive>
<ul>
<li ng-repeat="list in array">{{list.name}}</li>
</ul>
</directive>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>