这是 html:
<body ng-app="myCatApp">
<div ng-controller="catagoryController">
<add-remove-lister list="catagories"></add-remove-lister>
</div>
</body>
这是 JS:
app.controller('catagoryController', ['catagoryList', '$scope', function(catagoryList, $scope) {
$scope.catagories = catagoryList.catagoryList;
}]);
app.directive('addRemoveLister', [function () {
return {
scope: {
list: '='
},
template: function(tElement, tAttrs, scope) {
templateHTML = '<ul>';
var list = scope.list;
for (o = 0; o < list.length; o++) {
var curObject = scope.list[o];
templateHTML +='<li ng-repeat="listItem in list"><button type="button" ng-hide="listItem.userSelected" ng-click="addToList()">Add</button>';
templateHTML +='<button type="button" ng-hide="listItem.userSelected" ng-click="removeFromList()">Remove</button>{{listItem.text}}';
for (var prop in curObject) {
if (curObject.hasOwnProperty(prop) && prop.constructor === Array) {
templateHTML += '<add-remove-lister list="listItem.'+ prop +'"></add-remove-lister>';
}
}
templateHTML += '</li>';
}
templateHTML += '<ul>';
return templateHTML;
}
}
}]);
代码无法正常工作。当我在指令中设置断点时,我可以看到列表只是字符串“catagories”。我希望它是 Controller 范围内的类别对象...
让我扩展一下我正在尝试做的事情:
我正在尝试构建一个指令,它将接受任何数组并从中生成一个列表。假设是: 1) 数组中的所有元素都将是至少具有属性 {text : 'text', userSelected: 'bool'}
的对象当指令遇到列表中具有属性的对象时,该对象本身就是一个数组(也假设该对象包含具有上述两个属性的对象),它需要在该数组上递归调用自身。
该指令还需要在每个列表项旁边显示按钮,以允许用户更改对象上的 userSelected 属性(从而将其添加到用户“选项”中)
最佳答案
在你的模板函数中尝试一下这个
template: function(tElement, tAttrs, scope) {
templateHTML = '<ul>';
templateHTML +='<li ng-repeat="listItem in list"><button type="button" ng-hide="listItem.userSelected" ng-click="addToList()">Add</button>';
templateHTML +='<button type="button" ng-hide="listItem.userSelected" ng-click="removeFromList()">Remove</button>{{listItem.text}}';
templateHTML += '<add-remove-lister ng-repeat="(key, val) in listItem" ng-if="val.length" list="val"></add-remove-lister>';
templateHTML += '</li>';
templateHTML += '<ul>';
return templateHTML;
}
请注意,您可能只需使用模板即可完成上述操作,模板功能并不是真正必要的。
模板功能的主要原因是允许您修改原始 HTML 的 DOM,或者从原始元素中提取部分以进行手动嵌入。
此外,我已经在您的指令中看到了一些问题(您在模板中引用的函数必须在指令的范围内定义,并且由于您使用的是隔离范围,因此您无法在您的父作用域。您还必须将这些方法作为指令的属性传递,或者使用其他机制来添加或删除元素。
这是一个Working Plunk .
关于javascript - Angular Directive(指令)无法识别属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28446402/