Ng-model does not update controller value

alchemication picture alchemication · Sep 27, 2012 · Viewed 255.4k times · Source

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 ;]

Answer

Will Stern picture Will Stern · Mar 31, 2014

"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