In my Angular 1.5 app (a SPA), I use user profile information on every "page" of the app. So, in my app.js file, I include the following code:
$http.get(API_URL + "/user")
.then(function success(response){
$rootScope.userInfo = response.data;
},
function error(response){
});
And then in each component's controller and template, I make reference to this object like the following:
<img class="profile icon" ng-src="{{$rootScope.userInfo.profile_photo}}">
However, the image never shows up. I assume because the callback setting the $rootScope.userInfo from the response is called after the template has been loaded. How do I ensure it gets updated when the response comes in from the GET call?
EDIT - Here's more info, since the answers coming in about "don't use $rootScope in the view" isn't working for me. Making the changes suggested doesn't work. Do I need to reference $ctrl in this case?
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;
$rootScope, i.e. tryng-src="{{userInfo.profile_photo}}".$rootScope. Using$rootScopeis considered by many to be an anti-pattern anyway; It is recommended to use a service to store persistent data, and a requirement to use a service when in combination with components. While you might be able to use$rootto get around this restriction, this is not recommended behavior.