gpt4 book ai didi

javascript - Angular : parent directive isn't affected by changes in its child

转载 作者:行者123 更新时间:2023-12-02 15:25:18 25 4
gpt4 key购买 nike

我有一个 categoryList 指令,用于生成类别选择框。该指令工作正常,当我选择一个类别时,ngModel 中提到的外部 Controller 作用域属性会正确更新。但是,当我将 categoryList 放入另一个指令 (subCategoryList) 中时,subCategoryList 的范围未正确更新。

您可以在这段代码中看到这个有问题的行为:在第一个选择框中,您可以看到任何更改都将在外部范围中更新,但在第二个选择框中,更改“卡”在 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="angular.js@1.*" 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>
有人知道这里可能出现什么问题吗?

最佳答案

这是与指令 subCategoryList 中的 ng-if 相关的范围问题。如果删除它,代码就会开始工作。

关于javascript - Angular : parent directive isn't affected by changes in its child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33742386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com