在ngChange函数中获取ngModel的值

时间:2016-02-08 23:57:34

标签: angularjs angular-ngmodel

给定ngModel的输入,如何在ngChange函数中获取viewValue?

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

我试过了:

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

但是返回undefined。

1 个答案:

答案 0 :(得分:2)

检查此示例并验证您的代码:

&#13;
&#13;
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) {
    $scope.list.push(value);
  }
  
});
&#13;
<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS</title>
    <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>
  </head>
  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    
    <input type="text" ng-model="getMyObject().value" ng-change="insert(1, getMyObject().value)" />
    
    <br>

    <pre>myObj = {{myObj|json}}</pre>
    <pre>list = {{list|json}}</pre>
  </body>
</html>
&#13;
&#13;
&#13;

绑定了name指令的属性ng-model必须是可访问的:必须将其引用到范围内的对象。