AngularJS stuck in module - angularjs

app.controller('TableContent', ['$http', '$scope', '$window',
function ($scope, $window) {
console.log("I'm in TableContent");
$scope.EditSaverCommit = function () {
console.log("I'm in EditSaverCommit");
EditIndex = $scope.$index;
EditProjectID = $scope.project.ID;
console.log("Scope has"+$scope.project.Name);
EditProject = $scope.project.Name;
console.log("EditProject has "+EditProject);
};
$scope.DeleteProjectCommit = function () {
console.log("I'm in DeleteProjectCommit");
$window.Project.splice($scope.$index, 1);
ProjectLength = Project.length;
PostData = "";
$scope.Project = $window.Project;
PostData = $scope.Project.ID;
$http.get("https://localhost:44377/project/DeleteProject/"+PostData).then(function (response) {
console.log("I'm in DeleteProject");
$window.Project = response.data;
});
PostData = "";
console.log("I'm not in TableContent");
};
}]);
Hello all, I've had an issue with this snippet when it comes to loading my page.
After the entire page loads, all of my other http.get requests are down ever since I modified this part to accept http.get.
It doesn't print the "I'm not in TableContent" after full load and all other http.get requests are paralyzed but do print their respective console.log() messages.

Parameter $http is missing as function argument:
app.controller('TableContent', ['$http', '$scope', '$window',
function ($http, $scope, $window) {
...
};
}]);
This cracks the dependency injection...

Related

Passing data between angularjs modues/controllers

So I have two modules each one with one with its own controller and I need to pass an object between them, I seen this can be done with a service, I tried some stuff but I keep getting an "$injector" error in the second module/controller. Please help fix this.
This is my first module/controller with its service:
var appIndex = angular.module("AppIndex", ['datatables', 'datatables.bootstrap', 'ui.select']);
appIndex.service('sharedData', function () {
this.data = {};
this.setData = function (newData) {
this.data = newData;
return this.data;
};
this.getData = function () {
return this.data;
};
});
appIndex.controller("IndexController", function ($scope, $http, $window, sharedData) {
sharedData.setData($scope.referencia);
});
And this is my second module/controller:
var appCna = angular.module("AppCna", ['ui.select', 'AppIndex']);
appCna.controller("CnaController", function ($scope, $http, $window, sharedData) {
$scope.referencia = sharedData.getData();
});
You need to call setData in your first controller
appIndex.controller("IndexController", function ($scope, $http, $window, sharedData) {
sharedData.setData($scope.referencia);
});
So in the end I finally stop trying to use a service to my purpose of passing an object between two modules and what I did was to use the LocalStorage function.

factory is unable to convey data to another controller

I am building a spa with angular and slim framework. As per the bellow mentioned code, what i am trying to do is, login page controller will pass data to landing page controller upon successful submission of user/psw. When i place the factory outside the http call/ log in function it gets the data but on the landing page factory does not deliver the data. And when i place it inside it stops to work. Please help me....
this factory is for sharing data across controllers
appDls.factory('sharedFactory', function () {
var dataTobeShared = {};
var interface = {};
interface.add = function (d) {
dataTobeShared = d;
}
interface.put = function () {
return dataTobeShared;
}
return interface;
});
this controller is for the main portal user redirection and portal rendering
appDls.controller('DlsappController', ['$scope', '$state', 'multipartForm', 'sharedFactory', '$window', function ($scope, $state, multipartForm, sharedFactory, $window) {
$scope.Userdata = [];
$scope.login = function () {
var url = "../scripts/routes.php/authen";
multipartForm.post(url, $scope.login).then(function (d) {
$scope.Userdata.push(d.data[0]);
sharedFactory.add($scope.Userdata);
$window.location.href = '../portal/landing.php';
});
}
}]);
this controller is for landing page routing
appDls.controller('landingController', ['$scope', '$state', 'multipartForm', 'sharedFactory', function ($scope, $state, multipartForm, sharedFactory) {
$scope.UserInfo = sharedFactory.put();
$scope.$watch('UserInfo', function (newValue, oldValue) {
/*here we can use the user data from login page*/
if (newValue.length == 1) {
alert(newValue[0].fullname);
$state.go(newValue[0].proftype);
} else {
alert("user not logged in successfully!");
$state.go('default');
}
}, true);
}]);
When you do sharedFactory.add($scope.Userdata); your $scope.Userdata is another object, which is not watched by landingController. By reassigning dataToBeShared in sharedFactory.add function, you lose the reference to original object, so it is not reachable anymore from code.
To make landingController see the changes you need either to reimplement sharedFactory.add function to push values in sharedFactory.dataTobeShared array or use some event-based notification, not $watch.
Here is the jsfiddle to illustrate my words.
appDls.factory('sharedFactory', function () {
var dataTobeShared = {};
return
{
add: function (d) {
dataTobeShared = d;
}
put: function () {
return dataTobeShared;
}
}
});
appDls.controller('DlsappController', ['$scope', '$state', 'multipartForm', 'sharedFactory', '$window', function ($scope, $state, multipartForm, sharedFactory, $window) {
$scope.Userdata = [];
$scope.$watch('login',function () {
var url = "../scripts/routes.php/authen";
multipartForm.post(url, $scope.login).then(function (d) {
$scope.Userdata.push(d.data[0]);
sharedFactory.add($scope.Userdata);
$window.location.href = '../portal/landing.php';
});
}
}]);
appDls.controller('landingController', ['$scope', '$state', 'multipartForm', 'sharedFactory', function ($scope, $state, multipartForm, sharedFactory) {
$scope.UserInfo = sharedFactory.put();
$scope.$watch('UserInfo', function (newValue, oldValue) {
/*here we can use the user data from login page*/
if (newValue.length == 1) {
alert(newValue[0].fullname);
$state.go(newValue[0].proftype);
} else {
alert("user not logged in successfully!");
$state.go('default');
}
}, true);
}]);
The watcher needs to fetch the value from the factory on each digest cycle, and update the $scope variable.
appDls.controller('landingController', ['$scope', '$state', 'multipartForm', 'sharedFactory', function ($scope, $state, multipartForm, sharedFactory) {
//$scope.UserInfo = sharedFactory.put();
//$scope.$watch('UserInfo', function (newValue, oldValue) {
$scope.$watch(sharedFactory.put, function (newValue, oldValue) {
//UPDATE scope variable
$scope.UserInfo = newValue;
/*here we can use the user data from login page*/
if (newValue.length == 1) {
alert(newValue[0].fullname);
$state.go(newValue[0].proftype);
} else {
alert("user not logged in successfully!");
$state.go('default');
}
}, true);
}]);
The original code only set the scope variable once upon initialization of the controller. It needs to fetch the value from the factory on each digest cycle.

writing a simple Angular Service

OK, I've built services before but obviously I don't actually know what makes them tick, since I can't seem to debug this ultra-simple service call:
app.js:
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = [];
function dataService() {
console.log("I am the dataService and I am loaded");
var foo = 1;
function getData () {
return 2;
}
}
})();
I see this on-screen: I am Angular and I am working. so Angular is loading.
I see this in console: I am the dataService and I am loaded so the dataService is actually being loaded.
But then the console.log is:
undefined (line 8)
TypeError: dataService.getData is not a function (line 9)
What am I missing?
The previous answers are correct in that your $http injection was wrong, but you are also not attaching your service functions to the service:
function dataService() {
var dataService = this; //get a reference to the service
//attach your functions and variables to the service reference
dataService.foo = 1;
dataService.getData = function() {
return 2;
};
}
An Angular service is very simply an object class. It is also a singleton, meaning it's instantiated only once per run of your app. When the service is instantiated it is very much akin to calling the new operator on your dataService "class":
var $dataService = new dataService();
So, when you inject dataService into your controller, you are actually getting an instance, $dataService, of your dataService "class".
See this blog entry for further reading: https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider-5f426cfe6b8c#.sneoo52nk
You are missing the 2nd parameter $http in the function. The named parameters and the actual parameters in function need to be the same, same order and same number. What happened before is that dataService was being assigned an $http instance and the actual dataService was not injected at all because there was no 3rd parameter to inject it into.
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, $http, dataService) {
// ----was missing-----^
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
We have missed the second param '$http' in function. Just add the '$http' param, it should work fine
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope,$http, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
This is how I've been taught to set up services:
function dataService() {
var dataService = {};
var _foo = 1;
var _getData = function () { return 2; }
dataService.foo = _foo;
dataService.getData = _getData;
return dataService;
}
I believe this facilitates public/private methods/vars.
For reference, this is the full code accessing my service:
app.js:
var gridApp = angular.module('gridApp', []);
// create the controller and inject Angular's $scope
gridApp.controller('mainController', ['$scope', 'dataService', function($scope, dataService) {
// create a message to display in our view
$scope.message = 'Angular is working';
var init = function(){
getPackageData();
};
var getPackageData = function (){
return dataService.getData().then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
}
);
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = ['$http'];
function dataService($http) {
var dataService = {};
var _getData = function () {
return $http({
method: 'GET',
url: 'data/packages.json'
})
.then(function successCallback(response) {
return response;
},
function errorCallback(response) {
return response;
});
}
dataService.getData = _getData;
return dataService;
}
})();

Angularjs cannot get data from service

I'm trying to pass data from one controller to another using a service, however no matter what I'm trying it always returns 'undefined' on the second controller. Here is my service :
app.service('myService', ['$rootScope', '$http', function ($rootScope, $http) {
var savedData = {}
this.setData = function (data) {
savedData = data;
console.log('Data saved !', savedData);
}
this.getData = function get() {
console.log('Data used !', savedData);
return this.savedData;
}
}]);
Here is controller1 :
.controller('HomeCtrl', ['$scope','$location','$firebaseSimpleLogin','myService','$cookies','$window', function($scope,$location, $firebaseSimpleLogin, myService, $cookies, $window) {
loginObj.$login('password', {
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
myService.setData(user);
console.log('myservice:', myService.getData()); // works fine
}]);
And then controller2:
// Dashboard controller
.controller('DashboardCtrl', ['$scope','$firebaseSimpleLogin','myService',function($scope,$firebaseSimpleLogin, $location, myService) {
console.log('myservice:', myService.getData()); //returns undefined
}]);
That is simple code, unfortunately I've been struggling for a few hours now, any suggestion ? Thanks.
Created a fiddle here:
http://jsfiddle.net/frishi/8yn3nhfw/16
To isolate the problem, can you remove the dependencies from the definition for myService and see if that makes it work? Look at the console after you load the fiddle.
var app = angular.module('app', [])
.service('myService', function(){
this.getData = function(){
return "got Data";
}
})
I assume the issue is that you are returning this.savedData in the service. Try returning savedData.
this behaves different in Javascript than in other languages.

How can a service return data and multiple promises to a controller?

I have defined a service with functions like this:
angular.module('common').factory('_o', ['$angularCacheFactory', '$http', '$q', '$resource', '$timeout', '_u',
function ($angularCacheFactory, $http, $q, $resource, $timeout, _u) {
var _getContentTypes = function ($scope) {
var defer = $q.defer();
$http.get('/api/ContentType/GetSelect', { cache: _u.oyc })
.success(function (data) {
$scope.option.contentTypes = data;
$scope.option.contentTypesPlus = [{ id: 0, name: '*' }].concat(data);
$scope.option.sContentType = parseInt(_u.oyc.get('sContentType')) || 0;
defer.resolve();
})
return defer.promise;
};
return {
getContentTypes: _getContentTypes
}
}]);
I am calling this in my controller like this:
.controller('AdminProblemController', ['$http', '$q', '$resource', '$rootScope', '$scope', '_g', '_o', '_u',
function ($http, $q, $resource, $rootScope, $scope, _g, _o, _u) {
$scope.entityType = "Problem";
_u.oyc.put('adminPage', $scope.entityType.toLowerCase());
$q.all([
_o.getContentTypes($scope),
_o.getABC($scope),
_o.getDEF($scope)
])
Am I correct in saying this is not the best way to use a service. I think I should be returning the
content type data and then in the controller assigning to the scope not in the service.
But I am not sure how to do this as my service just returns a defer.promise and I am using $q.all so I think I should populate the scope after $q.all has returned success for every call.
Can someone give me some advice on how I should return data from a service with a promise and have it populate the $scope after $q.all has completed with all calls successful ?
You are absolutely correct in saying that the controller should really be doing this, it would be much cleaner to remove the passing around of your scope (and make it more re-usable). I don't know your exact use case and it is a little confusing to read, but you can do this by hooking into the promises that are created by $http, as well as still handling when all of the promises have been completed.
fiddle: http://jsfiddle.net/PtM8N/3/
HTML
<div ng-app="myApp" ng-controller="Ctrl">
{{model | json}}
<div ng-show="loading">Loading...</div>
</div>
Angular
var app = angular.module("myApp", []);
app.service("_service", ["$http", function (http) {
this.firstRequest = function () {
return http.get("http://json.ph/json?delay=1000")
.then(function (res) {
// manipulate data
res.data.something = new Date();
return res.data;
});
};
this.secondRequest = function () {
return http.get("http://json.ph/json?delay=2000")
.then(function (res) {
// manipulate data
res.data.something = 12345;
return res.data;
});
};
this.thirdRequest = function () {
return http.get("http://json.ph/json?delay=3000")
.then(function (res) {
// manipulate data
res.data.something = "bacon";
return res.data;
});
};
}]);
app.controller("Ctrl", ["$scope", "_service", "$q", function (scope, service, q) {
scope.loading = true;
scope.model = {};
var firstRequest = service.firstRequest();
var secondRequest = service.secondRequest();
var thirdRequest = service.thirdRequest();
q.all([firstRequest, secondRequest, thirdRequest]).then(function (responses) {
scope.model.first = responses[0];
scope.model.second = responses[1];
scope.model.third = responses[2];
scope.loading = false;
});
}]);

Resources