[javascript] Ng-model does not update controller value

Probably silly question, but I have my html form with simple input and button:

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

Then in the controller (template and controller are called from routeProvider):

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

Why do I see the view updated correctly but undefined in the console when clicking the button?

Thanks!

Update: Seems like I have actually solved that issue (before had to come up with some workarounds) with: Only had to change my property name from searchText to search.text, then define empty $scope.search = {}; object in the controller and voila... Have no idea why it's working though ;]

This question is related to javascript angularjs data-binding angular-ngmodel

The answer is


I came across the same issue when dealing with a non-trivial view (there are nested scopes). And finally discovered this is a known tricky thing when developing AngularJS application due to the nature of prototype-based inheritance of java-script. AngularJS nested scopes are created through this mechanism. And value created from ng-model is placed in children scope, not saying parent scope (maybe the one injected into controller) won't see the value, the value will also shadow any property with same name defined in parent scope if not use dot to enforce a prototype reference access. For more details, checkout the online video specific to illustrate this issue, http://egghead.io/video/angularjs-the-dot/ and comments following up it.


Since no one mentioned this the problem can be resolved by adding $parent to the bound property

<div ng-controller="LoginController">
    <input type="text" name="login" class="form-control" ng-model="$parent.ssn" ng-pattern="/\d{6,8}-\d{4}|\d{10,12}/" ng-required="true" />
    <button class="button-big" type="submit" ng-click="BankLogin()" ng-disabled="!bankidForm.login.$valid">Logga in</button>
</div>

And the controller

app.controller("LoginController", ['$scope', function ($scope) {
    $scope.ssn = '';

    $scope.BankLogin = function () {
        console.log($scope.ssn); // works!
    };
}]);

For me the problem was solved by stocking my datas into an object (here "datas").

_x000D_
_x000D_
NgApp.controller('MyController', function($scope) {_x000D_
_x000D_
   $scope.my_title = ""; // This don't work in ng-click function called_x000D_
_x000D_
   $scope.datas = {_x000D_
      'my_title' : "",_x000D_
   };_x000D_
_x000D_
   $scope.doAction = function() {_x000D_
         console.log($scope.my_title); // bad value_x000D_
         console.log($scope.datas.my_title); // Good Value binded by'ng-model'_x000D_
   }_x000D_
   _x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

I Hop it will help


I had the same problem.
The proper way would be setting the 'searchText' to be a property inside an object.

But what if I want to leave it as it is, a string? well, I tried every single method mentioned here, nothing worked.
But then I noticed that the problem is only in the initiation, so I've just set the value attribute and it worked.

<input type="text" ng-model="searchText" value={{searchText}} />

This way the value is just set to '$scope.searchText' value and it's being updated when the input value changes.

I know it's a workaround, but it worked for me..


Using this instead of $scope works.

_x000D_
_x000D_
function AppCtrl($scope){_x000D_
  $scope.searchText = "";_x000D_
  $scope.check = function () {_x000D_
    console.log("You typed '" + this.searchText + "'"); // used 'this' instead of $scope_x000D_
  }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app>_x000D_
  <div ng-controller="AppCtrl">_x000D_
    <input ng-model="searchText"/>_x000D_
    <button ng-click="check()">Write console log</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit: At the time writing this answer, I had much more complicated situation than this. After the comments, I tried to reproduce it to understand why it works, but no luck. I think somehow (don't really know why) a new child scope is generated and this refers to that scope. But if $scope is used, it actually refers to the parent $scope because of javascript's lexical scope feature.

Would be great if someone having this problem tests this way and inform us.


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.


"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


You can do that to enable search in ng-keypress enter for input text and in ng-click for the icon:

<input type="text" ng-model="searchText" ng-keypress="keyEnter(this,$event)" />
<button ng-click="check(searchText)">Check!</button>

in the controller
$scope.search = function (searchText) {
        console.log(searchText);
    }
    $scope.keyEnter = function (serachText,$event) {
        var keyCode = $event.which || $event.keyCode;
        if (keyCode === 13) {//KeyCode for Enter key
           console.log(searchText);
        }
    }

I had the same problem and it was due to me not declaring the blank object first at the top of my controller:

$scope.model = {}

<input ng-model="model.firstProperty">

Hope this will works for you!


I just had this very issue using a root_controller bound to the body-element. Then I was using ng-view with the angular router. The problem is that angular ALWAYS creates a new scope when it inserts the html into ng-view element. As a consequence, my "check" function was defined on the parent scope of the scope that was modified by my ng-model element.

To solve the problem, just use a dedicated controller within route-loaded html content.


Have a look at this fiddle http://jsfiddle.net/ganarajpr/MSjqL/

I have ( I assume! ) done exactly what you were doing and it seems to be working. Can you check what is not working here for you?


I was facing same problem... The resolution that worked for me is to use this keyword..........

alert(this.ModelName);


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to data-binding

Angular 2 Checkbox Two Way Data Binding Get user input from textarea Launch an event when checking a checkbox in Angular2 Angular 2 two way binding using ngModel is not working Binding ComboBox SelectedItem using MVVM Implement Validation for WPF TextBoxes Use StringFormat to add a string to a WPF XAML binding how to bind datatable to datagridview in c# How to format number of decimal places in wpf using style/template? AngularJS - Binding radio buttons to models with boolean values

Examples related to angular-ngmodel

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'" Get user input from textarea AngularJs - ng-model in a SELECT Angular bootstrap datepicker date format does not format ng-model value Radio Buttons ng-checked with ng-model How to set a selected option of a dropdown list control using angular JS Ng-model does not update controller value What's the difference between ng-model and ng-bind AngularJS : ng-model binding not updating when changed with jQuery