我想通过一个对象中的属性将一个$scope.data转换成指令,我可以用任何解决方案而不是通过分离的属性来实现下面的格式吗?
<custom-directive detail="{index:1, data: {{data}}}">
</custom-directive>并且作用域在指令中设置为下面
scope: {detail: "="}发布于 2015-12-01 16:14:50
一种解决方案可能是
return {
restrict: 'E',
require: 'ngModel',
scope: {
model: '=ngModel',
},
link: function(scope, element, attributes, ngModel) {
if (!ngModel) {
return;
}
console.log(scope.model); // your passed data
}
}然后
<custom-directive ngModel="data"></custom-directive>现在,您将把您的$scope.data传递给scope.model内部的指令。但请注意,指令中scope.model的任何更改也将反映在$scope.data中。
为了避免这种情况,您可以简单地更改ngModel。
return {
restrict: 'E',
scope: {
data: '=myData',
},
link: function(scope, element, attributes) {
console.log(scope.data); // your passed data
}
}然后
<custom-directive my-data="data"></custom-directive>发布于 2015-12-01 16:16:51
您仍然有在控制器中创建对象的解决方案:
$scope.detail = {index:1, data:$scope.data}; 并将其提供给您的指令:
<custom-directive detail="detail"></custom-directive>发布于 2015-12-01 16:37:08
你只需在你的对象中写入数据,它会自动从你的控制器中解析出来。如下所示:
HTML
<custom-directive detail="{index:1, data: data}">
</custom-directive>指令
myApp.directive('customDirective', function() {
return {
restrict:"AE",
scope:{
detail:"="
},
link:function(scope,ele,attrs) {
alert(JSON.stringify(scope.detail));
}
}
});Fiddle Demo
https://stackoverflow.com/questions/34015060
复制相似问题