我有一個categoryList
指令,該指令生成一個選擇框類別。此指令工作正常,當我選擇一個類別時,ngModel
中提到的外部控制器作用域屬性已正確更新。但是當我把categoryList
放在另一個指令(subCategoryList
)中時,subCategoryList
的範圍沒有正確更新。Angular:parent指令不受其子項更改的影響
您可以在此代碼片段中看到這個有問題的行爲:在第一個選擇框中,您可以看到任何更改將在外部範圍內更新,但在第二個選擇框中,更改會「卡住」categoryList
指令,並且不影響subCategoryList
angular.module('plunker', [])
.controller('MainCtrl', function($scope) {
}).directive('categoryList', function() {
return {
restrict: 'E',
template: 'categoryList debug: {{model}}<br/><br/><select ng-options="cat as cat.name for cat in categories track by cat.id" ng-model="model" class="form-control"><option value="">{{emptyOptLabel}}</option></select>',
scope: {
model: '=ngModel',
categories: '=?',
catIdField: '@',
emptyOptLabel:'@'
},
link: categoryListLink
};
function categoryListLink(scope, el, attrs) {
if (angular.isUndefined(scope.catIdField)) {
scope.catIdField = 'categoryId';
}
if(angular.isUndefined(scope.emptyOptLabel)){
scope.emptyOptLabel = 'category';
}
if(!scope.categories) {
scope.categories = [
{
'categoryId':123,
'name':'cat1',
'subCategories':[
{
'subCategoryId':123,
'name':'subcat1'
}
]
}
];
}
prepareCats(scope.categories);
function prepareCats(cats){
cats.forEach(function (cat) {
cat.id = cat[scope.catIdField];
});
return cats;
}
}
}).directive('subCategoryList', function() {
return {
restrict: 'E',
template: 'subCategoryList debug:{{model}}<br/><br/><category-list ng-if="parent && parent.subCategories.length !== 0" ng-model="model" categories="parent.subCategories" cat-id-field="subCategoryId" empty-opt-label="sub category"></category-list>',
scope: {
model: '=ngModel',
parent: '='
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="[email protected]*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as main">
Outer debug: {{main.cat}}<br/><br/>
<category-list ng-model="main.cat" empty-opt-label="category"></category-list><br/><br/>
<sub-category-list ng-model="main.subcat" parent="main.cat"></sub-category-list>
</body>
</html>
您是否期待在沒有選擇子卡的情況下,subCategories對象會更改? –
我希望當我選擇'subcat1'時'subCategoryList'的'model'範圍屬性會被更新,我會看到這個:'subCategoryList debug:{「subCategoryId」:123,「name」:「subcat1」,「 ID「:123}' – someone235