ng-model值始终未定义

时间:2016-04-08 09:59:22

标签: javascript angularjs

我正在尝试学习角度并拥有最简单的应用程序,只是一个计算器,它将2个值发送到后端API以供添加。

我在2个文本字段上有ng-model指令,默认值为'输入值'最初这个值出现在表单字段中。

然而,当我尝试获取我输入表单字段的值时,它们总是未定义的,只有一个变量或对象中的变量。

我真的不明白为什么会发生这种情况,并且任何非ng-model绑定到字段的变量都不是未定义的:

 var calculatorApp = angular.module('calculatorApp', [
'config',
'ngRoute',  
'calculatorControllers', 
'calculatorServices'
]);

calculatorApp.config(['$routeProvider',
 function($routeProvider) {
   $routeProvider.
     when('/calculator', {
       templateUrl: 'partials/calculator.html',
       controller: 'CalculatorCtrl'
     }).
     when('/about', {
       templateUrl: 'partials/about.html',
       controller: 'AboutCtrl'
     }).
  otherwise({
    redirectTo: '/calculator'
  });
 }]);

 calculatorControllers.controller('CalculatorCtrl', ['$scope', 'CalculatorService',
 function($scope, CalculatorService) {
$scope.orderProp = 'asc';
$scope.result = ' awaiting calculation';

$scope.sum = {
    val1: 'Enter Value',
    val2: 'Enter Value'
}   

$scope.add = function(val1, val2) {                 
    alert($scope.sum.val1); //always undefined even if form field shows value and so are val1 and val2 passed to this function from html page
    var promise = CalculatorService.add(val1, val2);

    promise.then(function successCallback(response) {               
        $scope.sum = response.data.result;      
    }, function errorCallback(response) {
        console.log('Error: ', response);           
    });             
};   
}]);


 <div class="container-fluid">
<div class="row">
<div class="col-md-2">      

</div>
<div class="col-md-10">
    <label>
        Value One: <input type="text" name="lastName" ng-model="sum.val1" ng-minlength="3" ng-maxlength="5" />
    </label>
    <label>
        Value Two: <input type="text" name="lastName" ng-model="sum.val2" ng-minlength="3" ng-maxlength="5" />
    </label>
    <button ng-click="add(sum.val1, sum.val2)">Add</button>
    <div name="result" id="result">The result is <span ng-bind="result"></span></div>
</div>   

1 个答案:

答案 0 :(得分:1)

您的DOM不了解您的控制器。

我认为您忘记在父ng-controller="CalculatorCtrl"上添加div

或许它可能没有写在你的问题中?