我有一个非常“简单”的目标:我有一种表单创建器,并且该指令预计会“呈现”表单的内容。
为此,我创建了一个自定义指令,我计划传递该对象并创建一个用于渲染槽模板的逻辑。但是,我无法将对象传递给自定义指令
HTML:
<div ng-controller="myController">
<p>Components starts</p>
<div ng-repeat="item in items">
<!-- <p>{{item}}</p> -->
<my-component obj="item" ></my-component>
</div>
<p>Components ends</p>
</div>
JS
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.items = [
{ type: 'TextArea', data: 'Somedata1', mandatory: true },
{ type: 'List', data: 'Somedata2', mandatory: false },
{ type: 'Select', data: 'Somedata3', mandatory: true }];
})
.directive('myComponent', function() {
return {
restric: 'E',
scope: { obj: '=obj' },
template: '<div> This is the template for {{obj.type}} </div>'
};
});
我已经用网上的不同示例多次编写和更改了代码,但两天后我无法使其工作(是的,这是可耻的)
我知道问题出在传递给指令时,因为如果我从 ng-repeat 中删除注释标记,数据会正确显示,但如果我尝试使用该指令,它就不起作用。
请谁能帮我解释一下为什么这不起作用以及我错过了什么?
最佳答案
感谢您提供jsfiddle。我不确定如果没有它我是否会发现问题。
原来您拼写错误restrict
(您在末尾遗漏了“t”),并且您需要在 View 中省略对scope
的引用。
查看您的更新(和工作)fiddle here 。
关于javascript - 如何正确地将对象传递给自定义指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31175529/