我有HTML代码:
wercker.yml
和控制器:
<div ng-controller="ProfileLeftMenu">
<li ng-class="{'active':selectedTab == 'personal'}" ng-click="selectedTab = 'personal'" class=""><a href="1">Personal</a>
</li>
</div>
所以,如果这样做:
$scope.selectedTab = 'first';
if ($routeParams.page) {
ajax.get(page, function (CbData) {
$scope.selectedTab = page;
});
}
模板HTML中的总是得到:{{selectedTab}}
答案 0 :(得分:1)
您需要在路线更改后立即使用新的$scope
更新$routeParams
变量。为此,您可以收听$routeChangeSuccess
事件。试试这个:
<强> app.js 强>
var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/test/:page', {
templateUrl: function(params) {
return 'pidat.html';
},
controller: 'MainCtrl'
});
}
]);
app.controller('MainCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
// when controller is loaded params are empty
console.log('on controller load $routeParams', $routeParams);
$scope.name = 'World';
// only after you have transitioned to the new
// route will your $routeParams change so we
// need to listen for $routeChangeSuccess
$scope.$on('$routeChangeSuccess', function(){
console.log('on $routeChangeSuccess load $routeParams', $routeParams);
if ($routeParams.page) {
$scope.name = $routeParams.page;
}
});
}]);
因此,对于您的原始示例,您可能需要执行以下操作:
$scope.selectedTab = 'first';
$scope.$on('$routeChangeSuccess', function(){
if ($routeParams.page) {
ajax.get(page, function (CbData) {
$scope.selectedTab = page;
});
}
});
答案 1 :(得分:0)
使用角度$ http服务($http.get()
),而不是ajax.get()
。否则,一旦HTTP响应到来并执行回调,Angular就不会意识到您对作用域所做的更改,除非您调用$scope.$apply()
。