[英]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.