Search code examples
angularjscontrollerangular-ngmodel

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


So I have this angular directive defined:

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 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.


Solution

  • 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.