Angularjs 指令,该指令需要从其父级检索数据以显示数据
我想写一个简单的指令,显示来自父级的数据列表 父控制器有如下功能 $scope.datas=[1,2,3,4] 我应该如何编写指令Angularjs 指令,该指令需要从其父级检索数据以显示数据,angularjs,directive,scopes,Angularjs,Directive,Scopes,我想写一个简单的指令,显示来自父级的数据列表 父控制器有如下功能 $scope.datas=[1,2,3,4] 我应该如何编写指令 使用独立的作用域并具有类似作用域:{display:'='} 使用子作用域并直接引用$scope.datas??我觉得那很难看。我希望重用该指令,因此我希望传递一个属性来指示应该使用哪个父字段。换句话说,我想对指令说,我的数据要么在$scope.datas中,要么在$scope.dumpthat中 谢谢 对此,我将使用隔离作用域。您可以在子对象中使用父作用域属性
- 使用独立的作用域并具有类似作用域:{display:'='}
- 使用子作用域并直接引用$scope.datas??我觉得那很难看。我希望重用该指令,因此我希望传递一个属性来指示应该使用哪个父字段。换句话说,我想对指令说,我的数据要么在$scope.datas中,要么在$scope.dumpthat中
谢谢 对此,我将使用
隔离作用域。您可以在子对象中使用父作用域属性,但由于Angular使用原型继承,因此您必须小心如何进行(以及如何进行)访问
以下是一个简单的指令:
HTML
<display-directive display="datas">Datas are:</display-directive>
数据包括:
指令
app.directive("displayDirective", function(...) {
return {
restrict: "E",
scope: {
display: "=",
},
// Transclude will take the inner html of your directive and add it to
// any div which contains the ng-transclude directive
transclude: true,
// replace will swap out the inner html of the directive scope with
// the template you assign
replace: true,
template: [
"<div class='data-class'>",
" <div class='data-prefix' ng-transclude></div>",
" {{ display }}",
"</div>",
].join("\n"),
link: function(scope, element, attributes) {
// Initialize your directive here!
}),
};
});
app.directive(“displayDirective”),函数(…){
返回{
限制:“E”,
范围:{
显示:“=”,
},
//Transclude将获取指令的内部html并将其添加到
//任何包含ng TRANCLUDE指令的div
是的,
//replace将用替换指令范围的内部html
//指定的模板
替换:正确,
模板:[
"",
" ",
“{{display}}”,
"",
].join(“\n”),
链接:功能(范围、元素、属性){
//在这里初始化您的指令!
}),
};
});