ng-model绑定的变量在controller中为undefined

举例来说有如下AngularJS代码:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('app', {
url: '/app',
abstract: true,
templateUrl: 'template/app.html'
})
.state('app.search', {
url: '/search',
views: {
'content': {
templateUrl: 'templates/search.html',
controller: 'SearchCtrl'
}
}
});

$urlRouterProvider.otherwise('/app/search');
});

angular.module('starter.controllers', [])
.controller('SearchCtrl', function($scope) {
$scope.onSearch= function() {
console.log($scope.keyword);
};
});

模板文件search.html内容如下:





这个时候无论在文本框中输入任何东西按“搜索”之后,keyword的值始终是undefined。不过如果在ion-content中增加ng-controller="SearchCtrl"之后则会正常赋值,但这样的话过于繁琐了。

正确的做法是,首先ng-model不要直接设置成字符串,而是设置成一个object对象,然后需要在controller对这个对象进行初始化。代码如下:

angular.module('starter.controllers', [])
.controller('SearchCtrl', function($scope) {
// 对query进行初始化
$scope.query = {};

$scope.onSearch= function() {
console.log($scope.query.keyword);
};
});

模板文件search.html内容如下:





参考资料:
ng-model is undefined in controller
Nested Scopes in AngularJS

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注