directive
。 budgetCategories
。我的Controller
看起来像
function BudgetController($scope, Budget, Category) {
$scope.budgetCategories = [];
}
和Directive
看起来像
angular.module('categoryListingDirective', []).directive('categoryListing', function (Category) {
return {
restrict: 'A',
replace: true,
require: true,
scope: {
budgetCategories: '='
},
templateUrl: '../static/partials/categoryListingForm.html',
link: function (scope, element, attrs) {
scope.recurring = true;
scope.allParentCategories = undefined;
scope.categories = Category.query(function () {
scope.allParentCategories = _.uniq(scope.categories, function (category) {
return category.parent;
});
console.log('all parent categories:', scope.allParentCategories);
});
scope.subCategories = function (parentCategoryName) {
return _.filter(scope.categories, function (category) {
return category.parent == parentCategoryName;
});
};
scope.addBudgetCategory = function () {
console.log('adding budgetCategory:', scope.amount);
scope.budgetCategories.push({
'amount': scope.amount,
'category': scope.subCategory ? scope.subCategory.name : '',
'parent_category': scope.parentCategory.parent,
'recurring': scope.recurring
});
};
}
}
});
我想确保指令使用来自budgetCategories
的{{1}}。
当我这样做时,我得到错误
Controller
问题
TypeError: Cannot read property 'push' of undefined
at Scope.scope.addBudgetCategory (http://localhost:5000/static/app/js/directives/categoryListing.js:28:39)
at http://localhost:5000/static/app/lib/angular/angular.js:10672:29
at http://localhost:5000/static/app/lib/angular/angular.js:18763:37
at Scope.$eval (http://localhost:5000/static/app/lib/angular/angular.js:12533:44)
at Scope.$apply (http://localhost:5000/static/app/lib/angular/angular.js:12631:41)
at HTMLButtonElement.<anonymous> (http://localhost:5000/static/app/lib/angular/angular.js:18762:39)
at HTMLButtonElement.x.event.dispatch (http://localhost:5000/static/app/lib/others/jquery-2.0.0.min.js:1321:108)
at HTMLButtonElement.y.handle (http://localhost:5000/static/app/lib/others/jquery-2.0.0.min.js:1255:106)
budgetCatgories
Controller
谢谢
更新
Directive
看起来像
html
答案 0 :(得分:4)
这一行...
scope: {
budgetCategories: '='
},
为指令创建隔离范围,因此其范围不会从父范围继承,因此无法访问budgetCategories
。你有几个选择...
1)不要通过从指令定义中删除scope: { ... }
行来创建隔离范围。
2)将budgetCategories
传递给指令......
<div class="budgetEdit" category-listing="budget" budget-categories="budgetCategories"></div>
3)使用$parent
访问父范围......
scope.$parent.budgetCategories.push({
'amount': scope.amount,
'category': scope.subCategory ? scope.subCategory.name : '',
'parent_category': scope.parentCategory.parent,
'recurring': scope.recurring
});