【问题标题】:ng-model values are always undefinedng-model 值始终未定义
【发布时间】:2016-04-08 09:59:21
【问题描述】:

我正在尝试学习 Angular 并拥有最简单的应用程序,只是一个计算器,它可以将 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>   

【问题讨论】:

  • 你能做一个jsfiddle吗?

标签: javascript angularjs


【解决方案1】:

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

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

或者它只是没有写在你的问题中?

【讨论】:

  • 对不起,我使用的是模板,这只是 html 的模板部分。我会将 app.js 添加到其中。它有点工作,因为总和值和默认值在页面加载时被放入表单字段中。
  • 如果我从表单字段中删除 ng-model 指令,那么这些值不再是未定义的,所以我不知道为什么,但它与 ng-model 相关联。
  • 你是说当输入没有用ng-model链接到模型时,它工作?
  • 你能告诉我们ng-controller指令在哪里吗?
  • 嗨,是的,我在前面的代码 sn-ps 中添加了这个:when('/calculator', { templateUrl: 'partials/calculator.html', controller: 'CalculatorCtrl' })。跨度>
猜你喜欢
  • 2016-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
相关资源
最近更新 更多