McFiddlyWiddly McFiddlyWiddly - 4 months ago 19x
AngularJS Question

How do I access and update ng-model in controller?

So I have this angular directive defined:

.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 ng-repeat="tag in vm.tagListFromDatabase">' +
'<li>{{tag}}</li>' + '</div>'+

controller: taggerController,
controllerAs: "vm",
restrict: "E"

function taggerController() {
this.tagListFromDatabase = ["Bridges","Arches","Roads","Towers"];
this.addTag = function(){

Console.log gives me undefined, doesn't print anything. I don't understand why it shouldn't.

Also, I'm using template like this because I couldn't figure out how to do templateUrl, but I can figure that out later I guess.


You are trying to access newTag property bound to controller (vm), however in template you bind ngModel to the scope object, not controller.

Correct code would be:

<input type="text" ng-model="vm.newTag">

Note, vm.newTag binds model to controller, while newTag alone binds to the scope.