在我的角1.5应用程序( SPA)中,我在应用程序的每个“页面”上都使用用户配置文件信息。因此,在我的app.js文件中,我包括以下代码:
$http.get(API_URL + "/user")
.then(function success(response){
$rootScope.userInfo = response.data;
},
function error(response){
});然后在每个组件的控制器和模板中,我引用这个对象,如下所示:
<img class="profile icon" ng-src="{{$rootScope.userInfo.profile_photo}}">然而,这张照片从未出现过。我假设是因为回调设置了来自响应的$rootScope.userInfo是在加载模板之后调用的。当响应从GET调用进入时,我如何确保它得到更新?
编辑-这里有更多的信息,因为关于“不要在视图中使用$rootScope”的答案并不适用于我。做出建议的改变是行不通的。在这种情况下,我需要引用$ctrl吗?
angular.module('xxx')
.component("navBar", {
templateUrl: "/components/navBar/navBar.html",
controller: NavBarController,
bindings: {
}
});
function NavBarController($rootScope, $scope, $uibModal, $timeout, $http, API_URL) {
var vm = this;发布于 2016-10-31 13:30:22
请记住,视图已经绑定到$scope,您永远不会编写以下内容
<img class="profile icon" ng-src="{{$scope.userInfo.profile_photo}}">相反,
<img class="profile icon" ng-src="{{userInfo.profile_photo}}">除隔离作用域外,所有作用域都具有继承,并且$rootScope位于该链的顶部,因此只要在该链写入中没有其他$scope具有userInfo属性。
<img class="profile icon" ng-src="{{userInfo.profile_photo}}">将指向$rootScope中的属性。
如果您在隔离作用域中,则可以编写
<img class="profile icon" ng-src="{{$root.userInfo.profile_photo}}">因为所有作用域,即使是孤立的,都有一个指向$root的$rootScope属性
检查这里
angular.module('app', [])
.controller('TestCtrl', function($scope) {
// An empty controller to create a new scope
// Only for demonstration of inheritance
})
.directive('directive', function() {
return {
restrict: 'E',
scope: {},
template: '<div>{{$root.userInfo.name}}</div>'
};
})
.run(function($rootScope) {
$rootScope.userInfo = {
name: 'John'
};
});<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div>{{userInfo.name}}</div>
<div ng-controller="TestCtrl">
{{userInfo.name}}
</div>
<directive></directive>
</div>
发布于 2016-10-31 13:14:29
就用吧,
<img class="profile icon" ng-src="{{userInfo.profile_photo}}">演示
发布于 2016-10-31 13:15:43
你不必把$rootScope放在心上--你应该这样写
<img class="profile icon" ng-src="{{userInfo.profile_photo}}">https://stackoverflow.com/questions/40342904
复制相似问题