$resource inside in Controller function - angularjs

I have an issue when putting $resource request inside of Controller function. It works directly from the controller, but doesn't inside the function.
Maybe someone know why? Thanks!
angular.module('Vote', ['ngResource']);
function VotesController($scope, $resource) {
$scope.simple = $resource('url'); // works
$scope.some_item = $scope.simple.get();
$scope.upvoteQuestion = function($scope, $resource) {
$scope.simple = $resource('url'); // gets error: undefined
$scope.some_item = $scope.simple.get();
}
}

The way you define your function upvoteQuestion means that it takes 2 arguments ($scope and $resource). You need to remove that:
angular.module('Vote', ['ngResource']);
function VotesController($scope, $resource) {
$scope.simple = $resource('url'); // works
$scope.some_item = $scope.simple.get();
$scope.upvoteQuestion = function() {
$scope.simple = $resource('url'); // gets error: undefined
$scope.some_item = $scope.simple.get();
};
}
It's a scope problem.
If you define your function with those arguments but don't actually give them when you call the function they'll be set as undefined and that's why you get that error.
If you declare the function without those arguments, as they're not set in the function, it will look for them in the parent scope (the Controller scope) and then find them.

Related

Angular - Moving function into a service

I have a function that I'm now needing to use in multiple page so decided to move into a service - however its not going as I'm expecting.
So in my HTML i have:
<li ng-init="bg = underQBar(work.options)">
Then in the controller (before I moved the common function) it looked like:
$scope.underQBar = function(toWorkArray) {
//some implementation, with a return at the end
}
Now I've made my service:
function barService($window){
var self = this;
self.getBarColours = function(toWorkArray) {
//copied the implementation with the return here
}
}
And therefore trying this in my controller:
$scope.underQBar = barService.getBarColours(toWorkArray);
However this doesnt work, its not getting the parameter I'm sending from the HTML - is this a trivial fix or something wrong with the implementation?
This is the problem:
$scope.underQBar = barService.getBarColours(toWorkArray);
Here, you're assigning the result of the service function call to $scope.underQBar, when you meant to assign it the function itself.
This should work:
$scope.underQBar = barService.getBarColours;
If you want to make it more clear to the reader that it's a function, just do:
$scope.underQBar = function (toWorkArray) {
return barService.getBarColours(toWorkArray);
}
Here is a correct definition for your service :
angular.module("myModule").factory("BarService", ["$window", function($window){
var service = {};
service.getBarColours = function(toWorkArray){
//copied the implementation with the return here
};
return service;
}]);
And here is a correct way to inject the service in your controller :
angular.module("myModule").controller("controllerName", ["BarService", function(BarService){
var self = this;
self.getBarColours = BarService.getBarColours;
}]);
and here is the way to use it:
<li ng-init="bg = controllerName.underQBar(work.options)">
Explanation :
A service or a factory in angular cannot be accessed by your view. Your view can only make a call to your controllers.
If your function should have been called by many controllers, you can put this function in a global controller that will be responsible for controlling your whole view.

how to pass values between functions in the same scope

I have 2 functions in the same controller and I am trying to pass the a value from one function to another. But I am getting an error TypeError: Cannot read property 'activeDataset' of undefined
Here is my code:
angular.module('daModule').controller("Controller1",Controller1);
Controller1.$inject = ['$scope', '$timeout'];
function Controller1($scope, $timeout) {
var ct = this;
ct.datasetName = "demo";
...
ct.activeDataset = function activeDataset(){
return ct.datasetName;
};
}
Here is my other function in the same file
function fn1(Controller1) {
...
var currentDataSet = Controller1.activeDataset();
...
}
Don't know where I am going wrong.
There are a couple of things going wrong here.
One is that the functions Controller1 and fn1 are being defined on the global name space. If another module were to use the same function names, there would be problems. We call this global name space pollution and it should be avoided.
The second problem is that in Controller1 the value of this is not defined until after the function is called. And when it is called, it is set to the local context of when it was called. Attaching properties to this in a function call does not make them available as a global property of the function. That is why you are getting "activeDataset undefined" in fn1.
To answer your question of how to pass values between functions in the same scope: The functions need to be inside the controller and they should put those values on the $scope.
angular.module("myApp").controller("myController", [$scope, myController($scope){
$scope.datasetName = "demo";
$scope.activeDataSet = function(){
return $scope.datasetName;
};
$scope.fn1 = function() {
return $scope.activeDataSet();
};
}]);

ngNewRouter Angularjs 1.4.4 is not able to call component controller methods after callback

Today I was working to migrate my existing Angular js ngRoute base code to ngNewRouter and got stuck in component controller. As per new apporach component controller doesn't have $scope, instead of it uses "this". It works fine for simple usecase. In my usecase for a particular component I make REST API call to get the data. All works but when callback happens then it is not identifying "this" defined object. Following is code snippet for more details.
Component Controller to make call to get data:
var ClubonboardingController = function ($location, ApplicationLoaderService, ApplicationConstants, $window, ResourceImplementation, $rootScope) {
//Launch Application
this.launchApplication = function () {
this.cacheLoaded = true;
};
//Method to initialize
this.init = function () {
//show loading screen
this.showLoadingScreen = true;
//Initilize Application cache
ApplicationLoaderService.initilizeApplicationCache($rootScope, "3252345", true, "en_US", function () {
this.launchApplication(); //This throws function not found exception
});
};
//Call init() to initialze the loading.
this.init();
};
app.controller("ClubonboardingController", ClubonboardingController);
ClubonboardingController.$inject = ['$location', 'ApplicationLoaderService', 'ApplicationConstants', '$window', 'ResourceImplementation', '$rootScope'];
Issue: After callback code thinks "this" as global javascript object, instead of "this" for this controller and not able to find anything defines in this controller and it throw exception at this.launchApplication(); .
Please help.
I think the problem is that what 'this' means changes depending on context. There seems to be a general recommendation to assign 'this' to a local variable and use the variable. Thanks to JavaScript closures, the value of 'this' is then retained.
Using a local variable called vm seems to be common, and replace all 'this.' with 'vm.' Your code would end up changing to
var ClubonboardingController = function ($location, ApplicationLoaderService, ApplicationConstants,
$window, ResourceImplementation, $rootScope) {
var vm = this;
//Launch Application
vm.launchApplication = function () {
vm.cacheLoaded = true;
};
//Method to initialize
vm.init = function () {
...
Hope this helps.

Adding function to controllers in AngularJs

I'm trying to add function to controller in angularJS, the way I think should be working but sadly not.
Here is my code.
//this is working.
$scope.adddata = function () {
$scope.names.push({name:$scope.newdata.name,city:$scope.newdata.city});
//$scope.names.push($scope.newdata);
}
//this is not working
function adddata() {
$scope.names.push({name:$scope.newdata.name,city:$scope.newdata.city});
//$scope.names.push($scope.newdata);
}
$scope.adddata = adddata();
Both functions above are in the definition of controller, hence $scope variable is available.
Can I only use $scope.functionname = functionname(){....}
or I can create a function and later assign it to controller / scope.
Do $scope.adddata = adddata; (no parentheses). Using the parentheses will assign the result of calling adddata() to the scope variable, which is undefined (adddata() does not return a value).
This would work:
$scope.adddata = adddata;
instead of:
$scope.adddata = adddata();
Don't invoke the function, pass a reference to it.

How to handle callback for JSONP inside angularjs

I have a working JSONP call inside a angularjs module to get working I defined the callback outside of the module (see below). I was unable to get the callback working inside the module ( callback not defined ).
How would I get the jsonp_callback(data) inside the angular module ?
function jsonp_callback(data) {
// returning from async callbacks is (generally) meaningless
alert('good');
console.log(data.found);
}
angular.module('me.services', [])
.factory('Products', ['$http', '$q', '$filter', function ($http, $q, $filter) { // Query API and return JSON.
return {
get: function () {
var _deferred = $q.defer(),
funds = [],
products = [];
var murl = "http://localhost:82/api/productlist/getitems";
$http.jsonp(murl + "?callback=jsonp_callback", null, function (result) {
alert('ts');
});
}
Depending on how you want to handle the data inside angular:
function jsonp_callback(data) {
// for binding to a service property
angular.element(document).injector().get('ServiceName').whatever = data
// for binding to a controller scope propery
angular.element('#someDiv').scope().whatever = data
...

Resources