我在ui-view中爲我的應用程序和嵌套控制器使用ui-router。我父控制器看起來是這樣的:無法訪問AngularJS中的作用域值。控制檯日誌返回undefined
'use strict';
angular.module("discussoramaApp").controller("mainController", ["RestFullResponse", "Restangular", "localStorageService", "$scope", function(RestFullResponse, Restangular, localStorageService, $scope){
var currentId = localStorageService.get("***");
var user = Restangular.one("users", currentId);
var Profile = user.get({}, {"Authorization" : localStorageService.get('***')}).then(function(profile) {
$scope.profile = profile;
});
}]);
而且我的孩子控制器:
'use strict';
angular.module("discussoramaApp").controller("getTopicsController", ["RestFullResponse", "Restangular", "localStorageService", "$scope", function(RestFullResponse, Restangular, localStorageService, $scope){
var topics = Restangular.all('topics');
var allTopics = topics.getList({},{"Authorization" : localStorageService.get('***')}).then(function(topics){
$scope.topics = topics;
});
console.log($scope); // this works
console.log($scope.profile); // this returns undefined
}]);
我有越來越爲孩子控制器配置文件中繼承$範圍值的問題。當我登錄$ scope時,配置文件清晰可見。
但是當我嘗試登錄$ scope.profile控制檯返回undefined。有任何想法嗎?
編輯:添加我的ui路由器配置。
angular.module("discussoramaApp").config(
function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/home');
$urlRouterProvider.when('', '/home');
$stateProvider
.state('main',{
url: '',
templateUrl: 'partials/main.html',
requireLogin: true
})
.state('main.home',{
url: '/home',
templateUrl: 'partials/main.home.html',
requireLogin: true,
title: 'Home'
});
}
);
而且相應的HTML文件:
// main.html
<div ng-controller="mainController">
<div class="container">
<div ui-view></div>
</div>
</div>
和子html部分:
// main.home.html
<div ng-controller="getTopicsController">
<div ng-repeat="topic in topics | filter:search">
<a ui-sref="main.topic({id: topic.id})">{{ topic.topic_title }}</a>
</div>
</div>
UPDATE:與子控制器設置這樣的守望者解決了這個。感謝@jonathanpglick和@Nix的幫助。
$scope.$watch('profile', function(profile) {
if(profile) {
$window.document.title = "Discussorama | " + profile.user.name;
}
});
請發佈一個blub,顯示你'ui-router'配置。 – Nix
添加了ui-router配置和部分。 –
謝謝。我在下面發佈了一個答案。 – Nix