alchemication alchemication - 3 months ago 16
AngularJS Question

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

Answer

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);
}