Home Ask Login Register

Developers Planet

Your answer is one click away!

Regis Silva February 2016

Get value of ngModel inside ngChange function

Given an input with ngModel, how can i get the viewValue inside ngChange function?

<input type="text" ng-model="getMyObject().value" ng-change="insert(1, 'my object property')" />

I have tried:

<input type="text" ng-model="getMyObject().value" ng-change="insert(1, getMyObject().value)" />

But return undefined.


beaver February 2016

Check this example and verify your code:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.list = [1, 5, 7];

  $scope.myObj = {value: 10};

  $scope.getMyObject = function() {
    return $scope.myObj;
  $scope.insert = function(pos, value) {
<!DOCTYPE html>
<html ng-app="myApp">
    <meta charset="utf-8" />
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
    <script src="app.js"></script>
  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <input type="text" ng-model="getMyObject().value" ng-change="insert(1, getMyObject().value)" />

    <pre>myObj = {{myObj|json}}</pre>
    <pre>list = {{list|json}}</pre>

The property name to which is bound your ng-model directive must be accessible: it has to be referred to an object in the scope.

Post Status

Asked in February 2016
Viewed 2,585 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life