如何访问和更新控制器中的 ng-model?
How do I access and update ng-model in controller?
所以我定义了这个 angular 指令:
angular.module('photoSynthesysApp')
.directive('tagList', function(){
return {
template: '<div class="tag-form"> <label> LABELS </label>'+
'<button class="btn-xsmall" ng-click="clicked = !clicked">+</button>' +
'<div ng-show="clicked">'+
'<input type="text" ng-model="newTag"> '+
'<button ng-click="vm.addTag()"> Add </button>' +
'</div>'+
'<ul>'+
'<div ng-repeat="tag in vm.tagListFromDatabase">' +
'<li>{{tag}}</li>' + '</div>'+
'</ul>'+
'</div>',
controller: taggerController,
controllerAs: "vm",
restrict: "E"
}
});
function taggerController() {
this.tagListFromDatabase = ["Bridges","Arches","Roads","Towers"];
this.clicked="false";
this.addTag = function(){
this.tagListFromDatabase.push(this.newTag);
console.log(this.newTag);
};
}
Console.log 给我未定义,不打印任何内容。我不明白为什么不应该。
此外,我正在使用这样的模板,因为我不知道如何做 templateUrl,但我想我以后可以弄清楚。
您正在尝试访问绑定到控制器 (vm
) 的 newTag
属性,但是在模板中您将 ngModel
绑定到范围对象,而不是控制器。
正确的代码是:
<input type="text" ng-model="vm.newTag">
注意,vm.newTag
将模型绑定到控制器,而 newTag
单独绑定到范围。
所以我定义了这个 angular 指令:
angular.module('photoSynthesysApp')
.directive('tagList', function(){
return {
template: '<div class="tag-form"> <label> LABELS </label>'+
'<button class="btn-xsmall" ng-click="clicked = !clicked">+</button>' +
'<div ng-show="clicked">'+
'<input type="text" ng-model="newTag"> '+
'<button ng-click="vm.addTag()"> Add </button>' +
'</div>'+
'<ul>'+
'<div ng-repeat="tag in vm.tagListFromDatabase">' +
'<li>{{tag}}</li>' + '</div>'+
'</ul>'+
'</div>',
controller: taggerController,
controllerAs: "vm",
restrict: "E"
}
});
function taggerController() {
this.tagListFromDatabase = ["Bridges","Arches","Roads","Towers"];
this.clicked="false";
this.addTag = function(){
this.tagListFromDatabase.push(this.newTag);
console.log(this.newTag);
};
}
Console.log 给我未定义,不打印任何内容。我不明白为什么不应该。
此外,我正在使用这样的模板,因为我不知道如何做 templateUrl,但我想我以后可以弄清楚。
您正在尝试访问绑定到控制器 (vm
) 的 newTag
属性,但是在模板中您将 ngModel
绑定到范围对象,而不是控制器。
正确的代码是:
<input type="text" ng-model="vm.newTag">
注意,vm.newTag
将模型绑定到控制器,而 newTag
单独绑定到范围。