[英]AngularJS calling a controller in a directive
到目前為止,我正在嘗試遵循的是一個相當不錯的教程,但是我在某個地方有些困惑,我需要創建一個指令來分隔大量html並使用控制器來生成數據。
var app = angular.module('newModule',[]);
app.directive('stateView', function(){
return{
restrict: 'E',
templateUrl: 'state-view.html',
controller: 'stateController',
controllerAs: 'stateCtrl'
}
});
app.controller('stateController',function(){
this.addStateTo = function(country){
if(!country.states){
country.states = [];
}
country.states.push({name: this.newState});
this.newState = "";
};
});
我的HTML狀態視圖看起來像這樣(C是來自另一個控制器的值,用於遍歷其他對象的列表)。
<div>
<input type="text" name="state" ng-model="stateCtrl.newState">
<a href ng-click="stateCtrl.addStateTo(c)"> Add State {{ stateCtrl.newState }}</a>
</div>
我對索引的唯一HTML引用如下:
<state-view></state-view>
它看起來很干凈,但是問題在於,除非我告訴DIV元素它是稱為StateController的ng-controller,否則它不會重新協調addStateTo函數。 這不是指令告訴HTML屬性的內容嗎?
嘗試以下方法(用$scope
代替this
):
app.controller('stateController',function($scope){
$scope.addStateTo = function(country){
if(!country.states){
country.states = [];
}
country.states.push({name: this.newState});
$scope.newState = "";
};
});
要么
app.controller('stateController',function(){
var vm = this;
vm.addStateTo = function(country){
if(!country.states){
country.states = [];
}
country.states.push({name: this.newState});
vm.newState = "";
};
});
您正在使用ControllerAs語法並適當地引用控制器上下文(即stateCtrl.newState和stateCtrl.addStateTo(c))。 問題是您沒有正確創建控制器上下文。 您的控制器代碼應如下所示:
app.controller('stateController', function() {
var vm = this;
this.addStateTo = function(country) {
if (!country.states) {
country.states = [];
}
country.states.push({
name: vm.newState
});
vm.newState = "";
};
});
這里的工作示例
嘗試在指令中添加true的bindto控制器。 上面的答案在解決您可能遇到的其他問題時也是正確的,即將您的問題映射到函數,盡管目前不這樣做可能不會引起問題。
var app = angular.module('newModule',[]);
app.directive('stateView', function(){
return{
restrict: 'E',
templateUrl: 'state-view.html',
controller: 'stateController',
controllerAs: 'stateCtrl',
bindToController: true
}
});
app.controller('stateController',function(){
var vm = this;
vm.addStateTo = function(country){
if(!country.states){
country.states = [];
}
country.states.push({name: vm.newState});
vm.newState = "";
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.