我正在尽可能密切地关注这些文档,但我不明白为什么这不起作用。当我需要退出 Controller 时,我尝试使用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">
效果很好。
编辑:根据要求,这里是 Controller :
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 语法允许您通过将 Controller 别名为 $scope
上的属性来避免直接连接到 $scope
。
即使用 controllerAs: 'dr'
时,您将获得一个属性 $scope.dr
。在 Controller 内部,您可以将其他属性直接映射到 Controller 实例,而不是 $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 中,即使您从未注入(inject) $scope
,您仍然可以访问这些值,因为 dr
是 $scope< 上的属性
.
ng-model="dr.formData.last_name"
关于javascript - Angular $routeprovider Controller 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30131278/