由于某种原因,$scope.username
未传递给我的控制器。点击registerUser()
$scope.username
未定义。我有一个范围,该函数只运行$ scope.username。
例如:
HTML:
<input bs-form-control
type="text"
ng-model="username"
label="Username"
/>
<button class="btn btn-primary" ng-click="registerUser()">Register</button>
控制器:
.controller("loginController", ['$scope',
function ($scope) {
$scope.registerUser = function(){
console.log($scope.username) // <=== undefined!
}
}])
我的控制器使用状态传递:
.state('register', {
url: "/register",
templateUrl: "/static/html/profile/register.html",
controller: "loginController"
})
答案 0 :(得分:2)
我认为bs-form-control
会创建一个新的孤立范围。你应该做的是使用你的范围内的对象(Does my ng-model really need to have a dot to avoid child $scope problems?)
或者使用AngularJS 1.2中引入的新“constroller as”语法。它也适用于ui-router!
请参阅此plunker:http://plnkr.co/edit/hkmMGbTtURSHDH84miiK?p=preview
.state('register', {
url: "/register",
templateUrl: "/static/html/profile/register.html",
controller: "loginController as loginCtrl"
})
<input bs-form-control type="text" ng-model="loginCtrl.username" label="Username" />
<button class="btn btn-primary" ng-click="loginCtrl.registerUser()">Register</button>
使用this
代替$scope
:
.controller("loginController", [
function () {
this.registerUser = function(){
console.log(this.username);
}
}
])