ng模型值总是未定义的

ng-model values are always undefined

本文关键字:未定义 模型 ng      更新时间:2024-03-17

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

我在两个默认值为"Enter value"的文本字段上有ng个模型指令,最初该值存在于表单字段中。

然而,当我试图将输入到表单字段中的值获取时,它们总是未定义的,使用单个变量或对象中的变量。

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

 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>   

您的DOM不知道您的控制器。

我想您只是忘记了在父div上添加ng-controller="CalculatorCtrl"

或者你的问题中没有写?