[英]Access parent scope in angular directive with template
我想重用表格来编辑一种类型的属性。 我有一个编辑列表:
ModelerControllers.controller('ModelController', ['$rootScope', '$scope', '$http', '$q',
function ($rootScope, $scope, $http, $q) {
...
$scope.mappingTypes = [
{"name": "mixpanel", "label": "Mixpanel"},
{"name": "mongo", "label": "Mongo"},
{"name": "slicer", "label": "Slicer"},
{"name": "sql", "label": "SQL"},
{"name": "", "label": "Other"}
];
...
}
]);
然后我有一条指令:
CubesModelerApp.directive("mappingEditor", function() {
return {
templateUrl: 'views/partials/mapping.html',
require: "ngModel",
scope: {
content: "=ngModel",
mappingTypes: "@mappingTypes"
},
link: function($scope, $element, $attrs) {
$scope.mappingTypes = $scope.$parent.mappingTypes;
}
}
});
用作:
<div mapping-editor ng-model='content.mapping'></div>
带有模板内容(相关块):
<!-- language: html -->
...
<select class="form-control"
ng-change="mappingTypeChanged(storeType)"
ng-model="storeType"
ng-options="f.name as f.label for f in mappingTypes">
</select>
...
这将产生一个空列表–好像mappingTypes
为空。
conent
的ngModel
已正确绑定。
如何在指令模板中访问全局(从父作用域之一)枚举? 还是有其他方法可以实现此目的,例如以不同的方式定义列表而不是应用程序$ scope变量?
编辑:这是一个小提琴 。
您的代码有几个问题:
1。
根据有关定制指令隔离范围的文档 :
=或= attr-在本地范围属性和通过attr属性值定义的名称的父范围属性之间建立双向绑定
(强调我的)
这意味着您需要引用一个属性,该属性的值是要共享的父范围属性的名称。 例如:
...
<editor ng-model="content" my-items="items"></editor>
...
scope: {
...
items: '=myItems'
},
另外,您可以在指令的link
函数中进行绑定:
...
<editor ng-model="content"></editor>
...
scope: {
content: 'ngModel'
// nothing `items` related here
},
...
link: function (scope, element, attrs) {
scope.items = scope.$parent.items;
}
2。
根据有关select
元素的文档 , ng-model
属性是必需的。 您必须将其添加到模板字符串中:
...
template:
...
'<select ng-model="selectedItem"...
3。
根据与select
元素相同的文档 , ng-options
属性的值必须具有您无法提供的指定格式之一(有关允许的格式的moe信息,请参阅文档)。 对于当前的简单情况,可以如下修改模板字符串:
...ng-options="item for item in items"...
\______/
|_____(you need to have a label)
另请参见此简短演示 。
尝试像这样设置参数的mapping-types
<div mapping-editor mapping-types='storeTypes' ng-model='content.mapping'></div>
如果您在指令中设置范围对象,则意味着该范围是隔离的,并且我不确定您是否能够到达父范围。 来自$ parent对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.