在我的 Angular 1.5 应用程序(SPA)中,我在应用程序的每个“页面”上使用用户个人资料信息。因此,在我的 app.js 文件中,我包含以下代码:
$http.get(API_URL + "/user")
.then(function success(response){
$rootScope.userInfo = response.data;
},
function error(response){
});
然后在每个组件的 Controller 和模板中,我引用该对象,如下所示:
<img class="profile icon" ng-src="{{$rootScope.userInfo.profile_photo}}">
但是,该图像从未显示。我认为是因为在加载模板后调用了从响应中设置 $rootScope.userInfo 的回调。当 GET 调用收到响应时,如何确保它得到更新?
编辑 - 这里有更多信息,因为关于“不要在 View 中使用 $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;
最佳答案
记住 View 已经绑定(bind)到$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}}">
因为所有作用域,即使是孤立的作用域,都有一个指向 $rootScope
的 $root
属性
检查这里
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>
关于javascript - Angular - $rootScope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40342904/