Angular 'this' doesn't assign value - angularjs

I have the following code, and the problem is, that value fetched from json is not assigned to the vm variable
(function() {
angular
.module('app', [])
.controller('theController', theController);
function theController($http) {
var vm = this;
vm.message = [];
vm.message2 = [];
fetchJSON();
console.log(vm.message);
vm.message2 = vm.message;
function fetchJSON() {
$http
.get('http://beta.json-generator.com/api/json/get/4y2l2jq8l')
.success(function(data) {
vm.message = data;
});
}
}
})();
The value I assign to vm.message in fetchJson method doesn't appear in the main view, so when I set message2 = message it is still empty.
Live demo: http://codepen.io/matt23/pen/PZbNQa?editors=101

Have you tried setting the vm.message2 inside the fetchJSON function?
You are setting the vm.message2 right after fetchSON() hence the success message has not yet bene defined.
function fetchJSON() {
$http
.get('http://beta.json-generator.com/api/json/get/4y2l2jq8l')
.success(function(data) {
vm.message = data;
// HERE
});
}
or you can add another callback:
.complete(function() {
});

Related

$scope not able to get data from factory using $http.get in Angularjs

<script>
var app = angular.module('myApp', ['ngMaterial']);
app.factory('factoryProvider', function ($http, $q) {
var facObj = {};
facObj.getLastWorkplace = $http.get('plugins/wcf-service/ServiceProvider.svc/getLastWorkPlacesJSON')
.then(function (response) {
return response.data;
});
return facObj;
});
app.controller('dashboardController', function ($scope, factoryProvider) {
factoryProvider.getLastWorkplace.then(function (successResponse) {
$scope.wp = successResponse;
console.log('inside');
console.log($scope.wp); // Return an object that I want
});
console.log('outside');
console.log($scope.wp); // $scope.wp is empty
});
The outside console log runs first, inside console log is the second. The problem is that $scope.wp can just get data in getLastWorkplace callback functions and it can not bind data to ng-model(using wp.property). How to solve it?
Thanks for your reading
You are assigning $scope.wp twice and the final assignment is the return value of your getLastWorkplace call (which you aren't returning anything.)
Change it to this...
factoryProvider.getLastWorkplace.then(function (successResponse) {
$scope.wp = successResponse;
});
or...
$scope.wp = factoryProvider.getLastWorkplace;
but not both.

AngularJS routing inside a factory

I want to create a factory for routing purposes. I want to encapsulate this in a factory because I want to exchange info from one page to another. I don't know if this is the best practice. Please tell me if there are other better ways.
This is my controller:
angular.module('app.core')
.controller('mainCtrl', ['ShowService', 'ChangeViews', function(ShowService, ChangeViews){
var vm = this;
vm.namespaces = [];
vm.servers = [];
vm.p4path = '';
vm.gitpckname = '';
vm.server = '';
vm.ns = '';
ShowService.getNamespaces().then(function(response){
var data = angular.fromJson(response.data);
angular.forEach(data.namespaces, function(value){
vm.namespaces.push(value);
vm.initNamespaceSelVal = vm.namespaces[0];
vm.ns = vm.namespaces[0];
});
});
ShowService.getServers().then(function(response){
var data = angular.fromJson(response.data);
angular.forEach(data.servers, function(value){
vm.servers.push(value);
vm.initServerSelVal = vm.servers[0];
vm.server = vm.servers[0];
});
});
vm.doClick = function(value){
if(value){
var body = {};
body['server'] = vm.server;
body['p4path'] = vm.p4path;
body['packagename'] = vm.gitpckname;
body['namespace'] = vm.ns;
ShowService.getBraches(body).then(function(response){
console.log(response);
//$location.path('/hidden');
//ChangeViews.changeView('/hidden');
});
};
};
}]);
In the above code, I injected two custom made factories into controller. The "ShowService" works properly but the "ChangeViews" returns some errors.
Using $location service inside the controller(the commented line) works.
The factory code is:
angular
.module('app.services')
.constant('BASE_URL', 'http://localhost:8066')
.factory('ShowService', dataService)
.factory('ChangeViews', changeViews);
function dataService($http, BASE_URL){.....}
function changeViews($location, view){
var data = {
'changeView': changeView,
};
function changeView(view){
return $location.path(view);
};
return data;
}
The path to the html template is routed.
The error I'm receiving when injecting the ChangeViews factory is:
"Error: [$injector:unpr] http://errors.angularjs.org/1.5.5/$injector/unpr?p0=viewProvider%20%3C-%20view%20%3C-%20ChangeViews
What I'm missing?
Thank you
The problem is that you don't have injectable service named view, hence the unknown provider error.
Remove view from changeViews parameters list:
function changeViews($location) {
var data = {
changeView: changeView
};
function changeView(view) {
return $location.path(view);
};
return data;
}

$http.get causing infinites calls (and errors) until computer crashes

I want to swap an array and get a json file, but don't know why nor where there's something wrong in my code (the service/controller part without an http request works though).
incriminated code
(function() {
(function() {
var JsonsService;
JsonsService = function($http) {
var pizze;
pizze = [];
return {
getPizze: function() {
$http.get('data/pizze-it.json').then(function(pizze) {
pizze = pizze.data;
});
}
};
};
JsonsService.$inject = ['$http'];
angular.module('myApp').factory('JsonsService', JsonsService);
})();
}).call(this);
(function() {
(function() {
var JsonsCtrl;
JsonsCtrl = function(JsonsService) {
var self;
self = this;
self.list = function() {
return JsonsService.getPizze();
};
};
JsonsCtrl.$inject = ['JsonsService'];
angular.module('myApp').controller('JsonsCtrl', JsonsCtrl);
})();
}).call(this);
Plnkr
I removed from app.js the entire block of code that is causing this error (service and controller), and placed it inside DontLoadThis.js (there's some markup to put back into main.html too)
This isn't necessarily the definite answer but there's a few things I've noticed that appear wrong.
Starting with your JsonsService:
JsonsService = function($http) {
var pizze;
pizze = [];
return {
getPizze: function() {
$http.get('data/pizze-it.json').then(function(pizze) {
pizze = pizze.data;
});
}
};
};
You're initialising a variable pizze but also using the callback variable pizze in the $http.get(). Instead I suggest:
var pizze = [];
...
$http.get('data/pizze-it.json').then(function(json_response) {
pizze = json_response.data;
});
This however is made redundant by the second issue: JsonsService.getPizze() doesn't actually return anything. A possible way around this would be to return the promise from getPizze() and deal with the result in the controller.
// in service
return {
getPizze: function() {
return $http.get('data/pizze-it.json');
}
};
// in controller
JsonsCtrl = function(JsonsService) {
var self;
self = this;
self.list = [];
JsonsService.getPizze().then(function (json_response) {
self.list = json_response.data;
});
};

Angularjs; use $http in service returns reference instead of actual data

I'm using the services directive in Angularjs not factory and I need to populate a json file to local variable;
/* Contains projects on the town */
leMaireServicess.service('cityService', function($http) {
// JSON regions and cities loader
this.cities = [];
// initCities
this.initCities = function() {
this.cities = $http.get('data/census/cities.js').success(function(data) {
return data;
});
return this.cities;
};
// Get city info
this.getCity = function() {
return this.cities;
};
});
And in my controller I have
// Saved game controller
leMaireControllers.controller('GameCoreCtrl', function($scope, cityService) {
/* Control the town project slides */
cityService.initCities();
$scope.city = cityService.getCity();
console.log($scope.city);
});
But instead of returning the actual data, it returns;
Object {then: function, catch: function, finally: function, success: function, error: function}
You can use a watch to make this work (see plunker)
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,cityService) {
//$scope.cities = [];
$scope.service = cityService;
cityService.initCities();
$scope.$watch('service.getCity()', function(newVal) {
$scope.cities = newVal;
console.log(newVal)
});
});
app.service('cityService', function($http) {
var that = this;
this.cities = [];
this.initCities = function() {
$http.get('data.js').success(function(data) {
that.cities = data.cities;
});
};
this.getCity = function() {
return this.cities;
};
});
$http returns a promise which is what you're setting this.cities to.
This might help explain more,
https://stackoverflow.com/a/12513509/89702
In your controller you should be able to do something like this...
cityService.initCity().then(function(data) { $scope.city = data; }
You are working with promises which represent the result of an action that is performed asynchronously. Try it this way:
leMaireServicess.service('cityService', function($http) {
this.promise = {};
// initCities
this.initCities = function() {
this.promise = $http.get('data/census/cities.js');
};
// Get city info
this.getCity = function() {
return this.promise;
};
});
And in the controller you need to put your code in a callback:
// Saved game controller
leMaireControllers.controller('GameCoreCtrl', function($scope, cityService) {
/* Control the town project slides */
cityService.initCities();
cityService.getCity().then(function(result){
$scope.city = result.data;
console.log($scope.city);
});
});

Calling service for factory in controller

I have a problem when calling a service created using .factory in my controller.
The code looks like the following.
Factory (app.js):
.factory('Database',function($http){
return {
getDatabase: function(){
var database = {};
$http.get('http://localhost:3001/lookup').
success(function(data){
database.companyInfo = data.info.companyInfo;
});
}).
error(function(data){
console.log('Error' + data);
});
return database;
}
};
})
Controller:
angular.module('webClientApp')
.controller('MainCtrl', function (Database,Features,$scope,$http) {
$scope.databaseString = [];
$scope.quarters = ['Q1','Q2','Q3','Q4'];
$scope.years = ['2004','2005','2006','2007','2008','2009','2010',
'2011','2012','2013','2014'];
$scope.features = Features.getFeatures();
$scope.database = Database.getDatabase();
console.log($scope.database);
Now when I inspect the element in Firebug I get the console.log($scope.database) printed out before the GET statement result. $scope.database is shown as an Object {} with all the proprieties in place.
However if I try to use console.log($scope.database.companyInfo) I get an undefined as result, while instead I should get that data.info.companyInfo' that I passed from theDatabase` service (in this case an array).
What is the problem here? Can someone help me?
(If you need clarifications please let me know..)
The $http.get() call is asynchronous and makes use of promise objects. So, based on the code you provided it seems most likely that you are outputting the $scope.database before the success method is run in the service.
I build all my service methods to pass in a success or failure function. This would be the service:
.factory('Database',function($http){
return {
getDatabase: function(onSuccuess,onFailure){
var database = {};
$http.get('http://localhost:3001/lookup').
success(onSuccess).
error(onFailure);
}
};
})
This would be the controller code:
angular.module('webClientApp')
.controller('MainCtrl', function (Database,Features,$scope,$http) {
$scope.databaseString = [];
$scope.quarters = ['Q1','Q2','Q3','Q4'];
$scope.years = ['2004','2005','2006','2007','2008','2009','2010',
'2011','2012','2013','2014'];
$scope.features = Features.getFeatures();
Database.getDatabase(successFunction,failureFunction);
successFunction = function(data){
$scope.database = data.info.companyInfo;
console.log($scope.database);
});
failureFunction = function(data){
console.log('Error' + data);
}
Change your code in the following way:
.factory('Database',function($http){
return {
getDatabase: function(){
return $http.get('http://localhost:3001/lookup');
}
};
})
Then get the response in controller(Promise chain)
Database.getDatabase()
.then(function(data){
//assign value
})
.catch(function(){
})

Resources