[英]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();
});
對角的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 = {};
...
現在,即使您從未注入$scope
,也可以在HTML中訪問這些值,因為dr
是$scope
的屬性。
ng-model="dr.formData.last_name"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.