console.log($scope.username)
<input ng-model="username" class="user-name" placeholder="Username / Email Address">
不确定为什么我的ng-model不起作用,我没有定义。但是当我用下面的ng-click测试时,它可以工作。
$scope.username = function(){
alert('hey')
}
<input ng-click="username()" class="user-name" placeholder="Username / Email Address">
这么奇怪,有什么想法吗?
答案 0 :(得分:0)
如果你想为ng-model分配一个函数,你需要使用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>
希望这会有所帮助!!