我得到了一个指令,该指令根据传递给它的变量类型来加载不同的模板。我还将变量患者和服务传递给指令的隔离范围。
.directive('serviceCharts', serviceCharts);
function serviceCharts() {
return {
restrict: 'E',
link: function (scope, element, attrs) {
if(attrs.type) {
scope.template = 'views/' + type + '.html';
}
attrs.$observe('type', function (type) {
if(attrs.type) {
scope.template = 'views/' + type + '.html';
}
});
},
template: '<div ng-include="template"></div>',
scope:{
patient:'=',
service:'='
}
};
}
在模板(例如views/myservice.html)中,我加载 Controller :
<div ng-controller="myCtrl as vm">
VIEW
</div>
在 Controller (myCtrl)中,我通过以下方式访问患者和服务:
service = $scope.$parent.$parent.service;
patient = $scope.$parent.$parent.patient;
这工作正常,但我不喜欢这种通过 $parent.$parent 访问变量的方式。这也扰乱了我的测试。
还有其他(更好)的方法吗?
谢谢!
最佳答案
您可以为 patient
创建一个包装对象& service
特性。可以命名为model
&然后将该模型对象提供给您的指令。
那么您当前方法的问题是,ng-include
为 template
创建子范围它在其中呈现。因此,当您将原始类型对象绑定(bind)传递给指令时,如果您要更改子作用域中的任何子原始类型绑定(bind)。它失去了绑定(bind),这就是为什么倾向于使用 $parent.$parent
符号完全绑定(bind)到原始源对象。
$scope.model = {
patient:'My Patient',
service:'My Service'
};
通过创建上述对象结构将确保您遵循 Dot Rule
。 Dot Rule
的使用将避免$parent.$parent
显式范围注释。
指令范围绑定(bind)将更改为以下
scope:{
model:'='
}
指令的用法如下所示
<service-charts type="{{'sometype'}}" model="model"></service-charts>
<小时/>
<小时/>
除了点规则之外,解决此类范围相关问题的另一种选择是遵循 controllerAs
图案。但是当你要使用隔离 scope
时与 controllerAs
你应该做 bindToController: true
选项设置为 true 以确保所有 scope
合并到 Controller 上下文中。
scope:{
patient:'=',
service:'='
},
controllerAs: '$ctrl',
bindToController: true
然后使用$ctrl
在每个指令作用域变量之前。
关于javascript - 将变量传递给指令 AngularJS 内的动态 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505908/