在我的情况下,ng 模型返回未定义

ng-model returned undefined in my case

本文关键字:模型 返回 未定义 ng 我的 情况下      更新时间:2023-09-26
console.log($scope.username)
<input ng-model="username" class="user-name" placeholder="Username / Email Address">

不知道为什么我的ng模型不起作用,我被定义不了。但是当我用下面的ng-click进行测试时,它可以工作。

$scope.username = function(){
        alert('hey')
}
<input ng-click="username()" class="user-name" placeholder="Username / Email Address">

太奇怪了,有什么想法吗?

如果你想给你的ng模型分配一个函数,你需要使用ng-model的getter setter选项

以下是来自angularjs网站的片段

视图

 <input type="text" name="userName"
             ng-model="user.name"
             ng-model-options="{ getterSetter: true }" />

控制器

var _name = 'Brian';

$scope.user = {
    name: function(newName) {
     // Note that newName can be undefined for two reasons:
     // 1. Because it is called as a getter and thus called with no arguments
     // 2. Because the property should actually be set to undefined. This happens e.g. if the
     //    input is invalid
     return arguments.length ? (_name = newName) : _name;
    }
  };

注意:对于绑定,您可以使用普通属性或 getter 二传手函数。您将无法使用其他类似事件的函数。 为此,您需要使用ng-click,ng-init等

进一步阅读

https://docs.angularjs.org/api/ng/directive/ngModel#binding-to-a-getter-setter

代码来实现您正在尝试执行的操作

<html ng-app="exampleApp">
<head>
    <title>Example</title>
</head>
<body ng-controller="defaultCtrl">
   <input ng-model="username" class="user-name" placeholder="Username / Email Address">
    <button ng-click="showName()">Show Name</button>
    <script src="bower_components/angular/angular.min.js"></script>
    <script>
angular.module('exampleApp', [])
    .controller('defaultCtrl', function($scope) {
        $scope.username = "";
        $scope.showName = function(){
            alert($scope.username)
        }
    });
</script>
</body>
</html>

希望这有帮助!!