Angular $routeprovider controllerAs 不工作
Angular $routeprovider controllerAs not working
我正在尽可能地关注文档,但我不明白为什么这不起作用。当我需要离开控制器时,我试图使用 controllerAs 而不是使用 $parent,但如果我无法弄清楚这一点,我将不得不坚持使用它。
路线:
.when('/user/:id', {
templateUrl: 'views/user.html',
access: { requiredLogin: true },
controller: 'UserCtrl',
controllerAs: 'dr'
查看:
<input type="text" class="form-control" id="last-name" placeholder="Last Name" ng-model="dr.formData.last_name">
如果我删除博士。并做
<input type="text" class="form-control" id="last-name" placeholder="Last Name" ng-model="formData.last_name">
它工作正常。
编辑:根据要求这里是控制器:
angular.module('angularWebappSeedApp')
.controller('UserCtrl', function ($scope,$routeParams,$http, API_URL) {
$scope.userId = $routeParams.id;
$scope.formData = {};
$scope.activeTab = 0;
var init = function(){
$http.get(API_URL+'/admin/users/'+$scope.userId).then(function(response) {
$scope.formData = response.data;
});
};
init();
});
Angular 的 ControllerAs 语法允许您避免直接连接到 $scope
,方法是将您的控制器别名为 $scope
上的 属性。
即使用 controllerAs: 'dr'
时,您将得到 属性 $scope.dr
。在控制器内部,您可以将其他属性直接映射到控制器实例,而不是 $scope
。例如:
angular.module('angularWebappSeedApp')
.controller('UserCtrl', function ($routeParams,$http, API_URL) {
//no need to inject $scope here
var self = this; //create an alias to avoid closure issues
self.userId = $routeParams.id;
self.formData = {};
...
现在,在您的 HTML 中,您仍然可以访问这些值,即使您从未注入 $scope
,因为 dr
是 [=12 上的 属性 =].
ng-model="dr.formData.last_name"
我正在尽可能地关注文档,但我不明白为什么这不起作用。当我需要离开控制器时,我试图使用 controllerAs 而不是使用 $parent,但如果我无法弄清楚这一点,我将不得不坚持使用它。 路线:
.when('/user/:id', {
templateUrl: 'views/user.html',
access: { requiredLogin: true },
controller: 'UserCtrl',
controllerAs: 'dr'
查看:
<input type="text" class="form-control" id="last-name" placeholder="Last Name" ng-model="dr.formData.last_name">
如果我删除博士。并做
<input type="text" class="form-control" id="last-name" placeholder="Last Name" ng-model="formData.last_name">
它工作正常。
编辑:根据要求这里是控制器:
angular.module('angularWebappSeedApp')
.controller('UserCtrl', function ($scope,$routeParams,$http, API_URL) {
$scope.userId = $routeParams.id;
$scope.formData = {};
$scope.activeTab = 0;
var init = function(){
$http.get(API_URL+'/admin/users/'+$scope.userId).then(function(response) {
$scope.formData = response.data;
});
};
init();
});
Angular 的 ControllerAs 语法允许您避免直接连接到 $scope
,方法是将您的控制器别名为 $scope
上的 属性。
即使用 controllerAs: 'dr'
时,您将得到 属性 $scope.dr
。在控制器内部,您可以将其他属性直接映射到控制器实例,而不是 $scope
。例如:
angular.module('angularWebappSeedApp')
.controller('UserCtrl', function ($routeParams,$http, API_URL) {
//no need to inject $scope here
var self = this; //create an alias to avoid closure issues
self.userId = $routeParams.id;
self.formData = {};
...
现在,在您的 HTML 中,您仍然可以访问这些值,即使您从未注入 $scope
,因为 dr
是 [=12 上的 属性 =].
ng-model="dr.formData.last_name"