[英]AngularJS: Two-way data binding not finding model in Controller
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
});
};
}
}
});
我想確保指令使用Controller
budgetCategories
。
當我這樣做時,我得到錯誤
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)
題
Directive
使用Controller
budgetCatgories
謝謝
更新
的html
看起來像
<div class="budgetEdit" category-listing="budget">
</div>
這條線...
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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.