在我的Angular 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调用响应时,如何确保更新?
编辑 - 以下是更多信息,因为关于&#34;未在视图中使用$ rootScope的答案&#34;我不是在为我工作。建议进行更改并不起作用。在这种情况下我需要引用$ 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;
答案 0 :(得分:2)
答案 1 :(得分:2)
请记住,视图已经绑定到$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>
答案 2 :(得分:0)
你不必将$rootScope
放在视野中
你应该这样说
<img class="profile icon" ng-src="{{userInfo.profile_photo}}">