Ng-model does not update controller value Ng-model does not update controller value angularjs angularjs

Ng-model does not update controller value


"If you use ng-model, you have to have a dot in there."
Make your model point to an object.property and you'll be good to go.

Controller

$scope.formData = {};$scope.check = function () {  console.log($scope.formData.searchText.$modelValue); //works}

Template

<input ng-model="formData.searchText"/><button ng-click="check()">Check!</button>

This happens when child scopes are in play - like child routes or ng-repeats.The child-scope creates it's own value and a name conflict is born as illustrated here:

See this video clip for more: https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s


Controller as version (recommended)

Here the template

<div ng-app="example" ng-controller="myController as $ctrl">    <input type="text" ng-model="$ctrl.searchText" />    <button ng-click="$ctrl.check()">Check!</button>    {{ $ctrl.searchText }}</div>

The JS

angular.module('example', [])  .controller('myController', function() {    var vm = this;    vm.check = function () {      console.log(vm.searchText);    };  });

An example: http://codepen.io/Damax/pen/rjawoO

The best will be to use component with Angular 2.x or Angular 1.5 or upper

########

Old way (NOT recommended)

This is NOT recommended because a string is a primitive, highly recommended to use an object instead

Try this in your markup

<input type="text" ng-model="searchText" /><button ng-click="check(searchText)">Check!</button>{{ searchText }}

and this in your controller

$scope.check = function (searchText) {    console.log(searchText);}


In Mastering Web Application Development with AngularJS book p.19, it is written that

Avoid direct bindings to scope's properties. Two-way data binding to object's properties (exposed on a scope) is a preferred approach. As a rule of thumb, you should have a dot in an expression provided to the ng-model directive (for example, ng-model="thing.name").

Scopes are just JavaScript objects, and they mimic dom hierarchy. According to JavaScript Prototype Inheritance, scopes properties are separated through scopes. To avoid this, dot notation should use to bind ng-models.