代码之家  ›  专栏  ›  技术社区  ›  Narendra Singh Rathore

获取angularjs中未定义的$scope变量

  •  0
  • Narendra Singh Rathore  · 技术社区  · 10 年前

    当我初始化 $scope.s 有一些价值,它工作正常。 但是,当它没有用如下所示的任何值初始化时,它会在控制台中生成错误: $scope。s未定义 单击事件绑定按钮

     var mainApp = angular.module('mainApp', ['ngRoute']);
    mainApp.controller('homeCtrl', ['$scope', '$http', function ($scope, $http) {
    
    
    $scope.title = 'Home page';
    $scope.s = '';
    $scope.m = '';
    $scope.subscribe = function () {
    
    
        console.log($scope.s); // undefined
    
    
    }
    }]);
    
    <div data-ng-app="mainApp" data-ng-controller="homeCtrl">
    <div>
        <h1>{{title}}</h1>
    </div>
    <div>
        <h3>Want to become a seller and earn more..?</h3>
        <p>Add your email and we will get in touch.</p>
        <div>
            <input type="email" data-ng-model="s" id="txtEmail" />
        </div>
        <div>
            <div>                
                <button data-ng-click="subscribe();">Send</button>
            </div>            
        </div>
    </div>
    <div>
        {{m}}
    </div>
    

    1 回复  |  直到 10 年前
        1
  •  3
  •   tylerwal    10 年前

    这个 $scope.s 变量未定义,因为您使用的输入类型为 email 并且具有无效电子邮件的值。

    这个“特性”似乎没有很好的文档记录,但angular文档中的示例 input[email] 清楚地显示了相同的行为: input[email] @ docs.angularjs.org ; 在他们的例子中尝试一个有效和无效的电子邮件地址,你会看到与你所看到的相同的行为。

    因此,您的选项是:切换到输入类型 text 或者除非电子邮件有效,否则计划您的模型未定义。

    angularjs的github中有一个问题,可以追溯到2012年,其行为相同:

    Binding doesn't work with input type="email"