Shared data between controllers using factory and promises - angularjs

Ok so there is a lot out there about sharing data between controllers using factory/service, but I'm not finding what applies to my issue. Either I'm interpreting the answers incorrectly or this is a valid question I'm about to ask! Hopefully the latter.
I would like controller 2 to recognize when a new http call has been made and the factory images object has been updated. at the moment it resolves once and then ignores any subsequent updates. What am i overlooking?
My view:
<div>
<ul class="dynamic-grid" angular-grid="pics" grid-width="150" gutter-size="0" angular-grid-id="gallery" refresh-on-img-load="false" >
<li data-ng-repeat="pic in pics" class="grid" data-ng-clock>
<img src="{{pic.image.low_res.url}}" class="grid-img" data-actual-width = "{{pic.image.low_res.width}}" data-actual-height="{{pic.image.low_res.height}}" />
</li>
</ul>
</div>
factory:
.factory('imageService',['$q','$http',function($q,$http){
var images = {}
var imageServices = {};
imageServices.homeImages = function(){
console.log('fire home images')
images = $http({
method: 'GET',
url: '/api/insta/geo',
params: homeLoc
})
};
imageServices.locImages = function(placename){
console.log('fire locImages')
images = $http({
method: 'GET',
url: '/api/geo/loc',
params: placename
})
};
imageServices.getImages = function(){
console.log('fire get images', images)
return images;
}
return imageServices;
}]);
controller1:
angular.module('trailApp.intro', [])
.controller('introCtrl', function($scope, $location, $state, showTrails, imageService) {
// run the images service so the background can load
imageService.homeImages();
var intro = this;
intro.showlist = false;
intro.data = [];
//to get all the trails based on user's selected city and state (collected in the location object that's passed in)
intro.getList = function(location) {
intro.city = capitalize(location.city);
intro.state = capitalize(location.state);
//get placename for bg
var placename = {placename: intro.city + ',' + intro.state};
imageService.locImages(placename);
... do other stuff...
controller2:
angular.module('trailApp.bkgd', [])
.controller('bkgdCtrl', ['$scope','imageService', 'angularGridInstance', function ($scope,imageService, angularGridInstance) {
$scope.pics = {};
imageService.getImages().then(function(data){
$scope.pics = data;
console.log($scope.pics);
});
}]);

Your controller2 implementation only got the images once, you probably need a $watch to keep to updated:
angular.module('trailApp.bkgd', [])
.controller('bkgdCtrl', ['$scope','imageService', 'angularGridInstance', function ($scope,imageService, angularGridInstance) {
$scope.pics = {};
$scope.$watch(function(){
return imageService.getImages(); // This returns a promise
}, function(images, oldImages){
if(images !== oldImages){ // According to your implementation, your images promise changes reference
images.then(function(data){
$scope.pics = data;
console.log($scope.pics);
});
}
});
}]);

Related

angularjs ---- In the following code, I can not get the value of avatarPath

console log
angular.module('Kinder.pages.member')
.controller('MemberInfoCtrl', MemberInfoCtrl);
function MemberInfoCtrl($scope,MemberModel,Constants,fileReader,$filter,AppUtils,$http,toastr,API) {
var vm = this;
vm.member = {};
vm.member.memberType = "1";
vm.member.memberSex = "1";
vm.member.avatarPath = "";
$scope.getFile = function () {
fileReader.readAsDataUrl($scope.file, $scope);
var fileInput = document.getElementById('uploadFile').files[0];
if(!AppUtils.isUndefinedOrNull(fileInput)){
var formData=new FormData();
formData.append("picUrl",fileInput);
$http({
........
}).success(function(data, status) {
console.log(data);
if(data.stat == 'success'){
//vm will have avatarPath value in there
console.log(vm);
vm.member.avatarPath = data.path;
//vm will have avatarPath value in there
console.log(vm);
}
}).error(function(data, status) {
});
}
};
$scope.submit = function() {
//vm had loss avatarPath ...
console.log(vm.member);
};
}
I do the function is to upload pictures before the preview, upload to the server to return to the path, assigned to vm。
But I can not get the avatarPath value outside the $ scope.getFile method。
I suspect that the problem of the scope of the problem, but I can not find a solution, I am the angular novice。
So who can tell me what this is for the reason。
I used google translation to describe the above questions,
I do not know if you understand me。。。
Anyway, thank you for taking the time to browse this question!
i fix it!
thanks for #JayantPatil reminders!
i am declaring controller in the route
.state('member.info', {
url: '/info/{memberId:string}',
params: {
memberId: null
},
templateUrl: 'app/pages/member/info/member-info.html',
controller: 'MemberInfoCtrl as vm'
});
and in the html , i use the ng-controller
<div class="userpic" ng-controller="MemberInfoCtrl as vm">
<input type="file" ng-show="false" id="uploadFile" ng-file-select/>
</div>
cause i duplicate declarations the controller , maybe the Scopes is Different,
that is all

Data is stuck in $http .then method

Hi I am trying to display my data but when i tried to display it on my html using angular data wont pass through. checked the console and data was there. here is my html.
<ion-view view-title="">
<ion-content>
<!-- <div class="cards">
<div class="item item-image">
<img src="img/banner-children.jpg"></img>
</div>
</div> -->
<div class="list card padding" ng-repeat="charity in charityList">
<a href="#/app/charitypage/{{charity.charity_id}}" class="positive ">
<img class="char-logo img-thumb" ng-src="{{charity.logo}}">
<div class="char-info">
<h3 class="char-name text-pink">
<i class="ion-chevron-right text-pink btn-category"></i>
{{charity.charity_name}}</h3>
<p class="dark">{{charity.description}}</p>
</div>
</a>
</div>
</ion-content>
and here is my controller
angular.module('subCategory.controllers', [])
.controller('subCatCtrl', function($scope, $state, $http) {
$scope.getCategoryList = function(category){
$scope.charityList = {};
var categoryListData = {
charityCategory : category
}
$http({
method: 'POST',
header: {'Content-Type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/filantrome/Main/getCategoryList',
data: categoryListData
}).then(
function success( response ) {
$scope.charityList= response.data;
console.log($scope.charityList);
$state.go('app.subcat');
},
function error( response ) {
$scope.charityList = response.data;
console.log($scope.charityList);
// handle error
}
);
console.log($scope.charityList);
};
});
i can see the data that i was requesting on the console.log() inside the success function. but when i get out of the .then(); function $scope.charityList is empty.
what am i missing here? thanks!
Seems problem is in state change. To fix this you can use service to store received JSON
angular.module('subCategory.controllers', []).service(charityService, charityService);
/* #ngInject */
function charityService($http) {
var charityList = [];
var service = {
getData: getData,
getCharityList: getCharityList
};
return service;
function getCharityList() {
return charityList ;
}
function getData(categoryListData) {
$http({
method: 'POST',
header: {'Content-Type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/filantrome/Main/getCategoryList',
data: categoryListData
}).then(
function success( response ) {
charityList = response.data;
console.log(charityList );
$state.go('app.subcat'); // you can also change state here
},
function error( response ) {
$scope.charityList = response.data;
console.log($scope.charityList);
// handle error
}
);
}
}
then post data with controller function
$scope.getCategoryList = function(category){
var categoryListData = {
charityCategory : category
}
charityService.getData(categoryListData);
}
after state changes controller will get charityList from service
angular.module('subCategory.controllers', []) .controller('subCatCtrl',
function($scope, $state, $http, charityService) {
$scope.charityList = charityService.getCharityList();
// ...
As you have posted your console.log output, I can see that you have a single object receiving and assigning to charityList but you have an ng-repeat on the element. So, I think you should change $scope.charityList = {}; to $scope.charityList = []; or you can output this variable in the html to see whats going on like {{charityList}}.

How to dynamical set de widgetDefinitions in malhar angular dashboard via rest client?

I have installed malhar-angular-dashboard module and I want to populate some widgetDefinitions with my rest data.
HTML
<div ng-controller="widgetCtrl">
<div dashboard-layouts="layoutOptions" class="dashboard-container"></div>
</div>
widgetRestService
.factory('widgetRestService',['$http','UrlService','$log','$q',
function($http,UrlService,$log,$q){
var serviceInstance = {};
serviceInstance.getInfo = function(){
var request = $http({method: 'GET', url: '/rest/widgets/getListInfoDashboards'})
.then(function(success){
serviceInstance.widgets = success.data;
$log.debug('serviceInstance.widgets SUCCESS',serviceInstance.widgets);
},function(error){
$log.debug('Error ', error);
$log.debug('serviceInstance.widgets ERROR',serviceInstance.widgets);
});
return request;
};
serviceInstance.getAllWidgets = function () {
if (serviceInstance.widgets) {
return serviceInstance.widgets;
} else {
return [];
}
};
return serviceInstance;
}])
My rest service returns me this array of 3 objects :[{"name":"widgetList","title":" "},{"name":"widgetPie","title":" "},{"name":"widgetTable","title":" "}]
OtherService
.factory("OtherService", ["widgetRestService", "$log", "$q",
function (widgetRestService, $log, $q) {
var deferred = $q.defer();
widgetRestService.getInfo().then(function () {
deferred.resolve(widgetRestService.getAllWidgets());
});
return deferred.promise;
}])
Controller
OtherService.then(function(response){
$scope.layoutOptions = { // layout with explicit save
storageId: 'demo-layouts-explicit-save',
storage: localStorage,
storageHash: 'fs4df4d51',
widgetDefinitions:response , //must be a list
defaultWidgets: [],
explicitSave: true,
defaultLayouts: [
{title: 'Layout 1', active: true, defaultWidgets: []}
]
};
$log.debug('layoutOptions =',$scope.layoutOptions);
});
Result
layoutOptions: Object{defaultLayouts:Array[1],
defaultWidgets:Array[0],
explicitSave:true,
storage:Storage,
storageHash:'fs4df4d51',
storageId: 'demo-layouts-explicit-save',
widgetDefinitions: Array[3]}
TypeError: Cannot read property '$$hashKey' of undefined
at Object.extend (http://localhost:9000/bower_components/angular/angular.js:406:14)
at Object.LayoutStorage (http://localhost:9000/bower_components/malhar-angular-dashboard/dist/malhar-angular-dashboard.js:1064:15)
I searched at line 2: Object.LayoutStorage and I found out this:
angular.extend(defaults, options); //options = undefined (should have some keys and my widgetDefinitions array)
angular.extend(options, defaults);
The options variable is undefined only when I want to setup the $scope.layoutOptions within the then callback function.
Any advice how to set / avoid this ?
The problem is that the dashboard-layouts directive will compile before the asynchronous call from OtherService has finished, which means $scope.layoutOptions will be undefined.
A simple solution is to prevent the dashboard-layouts directive from compiling before $scope.layoutOptions is available.
You can do this by using ng-if:
<div ng-if="layoutOptions" dashboard-layouts="layoutOptions" class="dashboard-container">
</div>

Angular call service on asynchronous data

I have a service that make some calls to retrieve data to use in my app. After I've loaded data, I need to call another service to make some operations on my data. The problem is that second service will not have access to the data of the first service.
I've made a plunker: plunkr
First service
app.factory('Report', ['$http', function($http,$q){
var Authors = {
reports : [],
requests :[{'url':'data.json','response':'first'},
{'url':'data2.json','response':'second'},
{'url':'data3.json','response':'third'}]
};
Authors.getReport = function(target, source, response, callback) {
return $http({ url:source,
method:"GET",
//params:{url : target}
}).success(function(result) {
angular.extend(Authors.reports, result)
callback(result)
}
).error(function(error){
})
}
Authors.startQueue = function (target,callback) {
var promises = [];
this.requests.forEach(function (obj, i) {
console.log(obj.url)
promises.push(Authors.getReport(target, obj.url, obj.response, function(response,reports){
callback(obj.response,Authors.reports)
}));
});
}
return Authors;
}])
Second service
app.service('keyService', function(){
this.analyze = function(value) {
console.log(value)
return value.length
}
});
Conroller
In the controller I try something like:
$scope.result = Report.startQueue('http://www.prestitiinpdap.it', function (response,reports,keyService) {
$scope.progressBar +=33;
$scope.progress = response;
$scope.report = reports;
});
$scope.test = function(value){
keyService.analyze($scope.report.about);
}
I think this is what you are going for? Essentially, you want to call the second service after the first succeeds. There are other ways of doing this, but based on your example this is the simplest.
http://plnkr.co/edit/J2fGXR?p=preview
$scope.result = Report.startQueue('http://www.prestitiinpdap.it', function (response,reports) {
$scope.progressBar +=33;
$scope.progress = response;
$scope.report = reports;
$scope.test($scope.report.about); //added this line
});
$scope.test = function(value){
$scope.example = keyService.analyze(value); //changed this line to assign property "example"
}
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<p>Progress notification : {{progress}}!</p>
<div ng-show="show">
<progress percent="progressBar" class="progress-striped active"></progress>
</div>
<pre>{{report}}</pre>
<pre>{{report.about}}</pre>
{{example}} <!-- changed this binding -->
</body>

AngularJS: model data from http call not available in directive

There seems to be a bug where model data fetched from an http call is present in the $scope but not in a directive. Here is the code that illustrates the problem:
Jsfiddle: http://jsfiddle.net/supercobra/hrgpc/
var myApp = angular.module('myApp', []).directive('prettyTag', function($interpolate) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
var text = element.text();
//var text = attrs.ngModel;
var e = $interpolate(text)(scope);
var htmlText = "<b>" + e + "</b>";
element.html(htmlText);
}
};
});
function MyCtrl($scope, $http, $templateCache) {
$scope.method = 'JSONP';
$scope.url = 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero';
$scope.fetch = function () {
$scope.code = null;
$scope.response = null;
$http({
method: $scope.method,
url: $scope.url,
cache: $templateCache
}).
success(function (data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
The HTML
<div ng-controller="MyCtrl">
<h1>Angular $http call / directive bug</h1>
<p>This fiddle illustrates a bug that shows that model w/ data fetched via an http call
is not present within a directive.</p>
<hr>
<h2>HTTP call settings</h2>
<li>Method: {{method}}
<li>URL: {{url}}
<br>
<button ng-click="fetch()">fetch</button>
<hr/>
<h3>HTTP call result</h3>
<li>HTTP response status: {{status}}</li>
<li>HTTP response data: {{data}}</li>
<hr/>
<h2>Pretty tag</h2>
<pretty-tag>make this pretty</pretty-tag>
<hr/>
<h3 style="color: red" >Should show http response data within pretty tag</h3>
[<pretty-tag>{{data}}</pretty-tag>] // <=== this is empty
</div>
Jsfiddle: http://jsfiddle.net/supercobra/hrgpc/
Any help appreciated.
You are replacing the content of the directive in your directive implementation. Since the $http request is async, the directive completes before the data is retrieve and assigned to the scope.
Put a watch on data variable inside the directive and then re-render the content, something like
scope.$watch(attrs.source,function(value) {
var e = $interpolate(text)(scope);
var htmlText = "<b>" + e + "</b>";
element.html(htmlText);
});
Based on #Marks feedback and your request i have update fiddle
http://jsfiddle.net/cmyworld/V6sDs/1/

Resources