Reputation: 586
I have a categoryList
directive that generates a select box of categories. This directive works fine and when I select a category, the outer controller scoped property mentioned in ngModel
is updated properly. But when I put categoryList
in another directive (subCategoryList
), the scope of subCategoryList
isn't updated properly.
You can see this problematic behavior in this snippet: In the first select box, you can see that any change will be updated in the outer scope, but in the second select box, the changes are "stuck" inside the categoryList
directive, and doesn't affect 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>
Upvotes: 0
Views: 92
Reputation: 2800
This is a scope issue related with ng-if
in directive subCategoryList
. If you remove it, the code starts working.
Upvotes: 2