Unknown scope provider $scope - javascript

I am trying to inject $scope but it's not working. This is my code:
var appCtrl = app.controller(
'AppCtrl',
function ($scope, $resource, $location, $route, sharedProperties) {}
);
appCtrl.prepData = function (
$q, $scope, $resource, $location, $route, sharedProperties) {}
I am trying to define a function after getting the appCtrl variable. But $scope wouldn't work there. Any idea how to resolve this issue?

Related

Reusing of functions which is defined between controllers

i would like to reuse the code defined between the controllers
.controller('GenericController', ['$scope', '$controller', '$rootScope', '$dialogs', '$state', '$http', '$modal', '$q', '$timeout', 'projectFactory', 'projectPromise', 'phaseFactory', 'buFactory', 'stakeholderGroupFactory', 'ldapFactory', 'genericFactory', 'User',
function ($scope, $controller, $rootScope, $dialogs, $state, $http, $modal, $q, $timeout, projectFactory, projectPromise, phaseFactory, buFactory, stakeholderGroupFactory, ldapFactory, genericFactory, User) {
$scope.testing = function() {
console.log("Hello");
};
}]);
You can use the factory and create the object for the function to reuse it.
app.factory("sample",function(){
return function() {
console.log("Hello");
};
})
else collating multiple common functions
app.factory("commonFunctions",function(){
commonFunction1(){
console.log("common func1")
}
commonFunction2(){
console.log("common func2")
}
return {
commonFunction1: commonFunction1,
commonFunction1: commonFunction2
};
})
Used the $controller for the importing this fixed my issue

AngularJS constants undefined is not an object

new to Angular and I'm trying to inject constants from a separate file. It seems to work with the DI, but when I try to use it, I get an error: Error: undefined is not an object (evaluating 'CApiEndpoints.authUrl').
I tried dot notation and brackets as suggested in Accessing AngularJS constants but continue to get the error.
The files are included in index.html, and DI doesn't complain.
index.html
<script type="text/javascript" src="js/angular/constants.js"></script>
<script type="text/javascript" src="js/angular/app.js"></script>
js/angular/constants.js
var app = angular.module('appConst', []);
app.constant('CApiEndpoints', {
authUrl: 'http://api.example.com/v1/',
...
});
and my js/angular/app.js
var app = angular.module('app', ['ngRoute', 'ngCookies', 'appConst', 'appServices']);
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', 'CApiEndpoints', function($scope, $route, $http, $cookies, $routeParams, $location, CApiEndpoints){
console.log(CApiEndpoints); // shows 'undefined'
$http({
method : 'GET',
url : CApiEndpoints.authUrl + 'user_info'
})
.then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
});
}]);
Any help would be appreciated. I've searched for the last 2 hours trying to figure this out.
While injecting dependencies inside your controller function using DI inline array annotation, they must follow the order how they are injected in array.
If you follow above rule you will come to know that you have two extra paramters inside your function, so you should remove those two unwanted ($routeParams, $location) dependency.
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', 'CApiEndpoints',
function($scope, $route, $http, $cookies, CApiEndpoints){
//controller code
}
]);
If you haven't added those parameter mistakenly, you should add those parameter on both side inside function & array.
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', '$routeParams', '$location', 'CApiEndpoints',
function($scope, $route, $http, $cookies, $routeParams, $location CApiEndpoints){
//controller code
}
]);

main module can't read my service

I'm trying to call a function which is in a service I have made. Whenever I try to search a username, I get an error which says "cannot read 'getUser' of undefined.
It shouldn't be undefined, I'm passing it an argument of a username it should be able to use. I can't seem to find out what's wrong with my service!
http://plnkr.co/edit/k4FD4eFuVKNvjEwKx2gs?p=preview
Any help to move forward with this would be appreciated :)
(function(){
var github = function($http){
var getUser = function(username){
$http.get("https://api.github.com/users/" + username)
.then(function(response){
return response.data; //still returns a promise
});
};
//angular invokes this, return an object which is github service
var getRepos = function(user){
$http.get(user.repos_url).then(function(response){
return response.data;
});
};
return {
getUser: getUser,
getRepos: getRepos
};
};
var module = angular.module("firstapp"); //get reference to existing module, NOT creating a new one
//register service with angular
module.factory("github", github);
}());
script.js
var app = angular.module("firstapp", []) //defining module, no dependencies (so far)
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
$scope.search = function(username) {
$log.info("Searching for "+username);
//the first parameter to .then is only invokes onusercomplete if the get is successful
//if error, it goes to second parameter which provdes error details
github.getUser(username)
.then(onUserComplete, onError);
if (countdownInterval){
$interval.cancel(countdownInterval);
$scope.countDown = null;
}
};
Problem lies in bad sequence of dependency injection arguments.
It is:
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github)
Should be:
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location","$http", function(
$scope,github,$interval, $log, $anchorScroll, $location, github,$http)
Parameters must be in correct order in DI.
If you encounter errors like:
"cannot read function name of undefined"
Then you should look for function calls and see what's wrong with object from which call goes.
In this case it's something wrong with github.
The issue is in your controller definition you don't have your dependencies line up
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
your dependencies are:
"$scope", "github", "$interval", "$log", "$anchorScroll", "$location"
but they are getting injected as
$scope, $http, $interval, $log, $anchorScroll, $location, github
You have to have the order line up otherwise you'll have the wrong dependency in the wrong variable, also you're not adding $http in your listed dependencies.
Your problem is in the getUser function. You are not returning a promise there. To work the way you are using it it should look like
var getUser = function(username){
return $http.get("https://api.github.com/users/" + username);
};
EDIT1
In your code, you were not returning a promise but the data returned by the promise.
Furthermore, you were returning that data from an anonymous callback (your function(response) {...}) to its caller (in your case then(...)
EDIT2
You should also check the way you are injecting your dependencies
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
should be
.controller("MainController", ["$scope", '$http', "$interval", "$log", "$anchorScroll", "$location", "github", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
EDIT3
You should also change the getRepos method like we did for the other one from
var getRepos = function(user){
$http.get(user.repos_url).then(function(response){
return response.data;
});
to
var getRepos = function(user){
return $http.get(user.repos_url);
});

AngularJS Service inside module not found

I am trying to modularize my AngularJS application and put some services inside a Module.
Everytime I try to reference my Service there is an error saying:
Unknown provider: UtilsProvider <- Utils <- benutzerUebersichtController
My code is:
var utils = angular.module('Utils',[]);
utils.service('UtilsService', function () {
this.CurrentUser = 'Hello World';
});
var verwaltungApp = angular.module('verwaltungApp', ['Utils'])
verwaltungApp.controller('benutzerUebersichtController', ['$scope', '$http', '$filter','Utils', benutzerUebersichtController]);
function benutzerUebersichtController($scope, $http, UtilsService) {
$scope.Test = UtilsService.CurrentUser;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="verwaltungApp">
<div ng-controller="benutzerUebersichtController">
<span>{{Test}}</span>
</div>
</div>
You din't inject the service in your controller properly.
This :
verwaltungApp.controller('benutzerUebersichtController', ['$scope', '$http', '$filter','Utils', benutzerUebersichtController]);
function benutzerUebersichtController($scope, $http, UtilsService) {
$scope.Test = UtilsService.CurrentUser;
};
should be:
verwaltungApp.controller('benutzerUebersichtController', ['$scope', '$http', '$filter','UtilsService', benutzerUebersichtController]);
function benutzerUebersichtController($scope, $http,$filter, UtilsService) {
$scope.Test = UtilsService.CurrentUser;
};
You are injecting this services in your controller:
['$scope', '$http', '$filter','Utils']);
But you are passing only these services:
function benutzerUebersichtController($scope, $http, UtilsService)
So your UtilsService is now your $filter inside your controller.
To correct you have to change to this.
function benutzerUebersichtController($scope, $http, $filter, UtilsService)

Using Angular services to hold commonly required data

I am currently writing my first application in Angular and have been very much enjoying all the framework has to offer so far. Like most newbies I set off building everything into a main controller, copying the tutorials. I am now seeing the error of my ways and refactoring.
My question is about services holding data that is commonly required among controllers.
I've now taken the data out of the 'main controller' and placed it into a service that I have injected into both controllers requiring access. Now though neither controller sees the functionality I've defined in the new service:
varianceService is not defined
Being new to this approach i welcome all and any help, aswell as help with my current problem, any comments on the best way to apply this approach would also be highly appreciated.
Thanks in advance.
Here is an example of the code:
var app = angular.module(
'VarianceAnalysis', ['ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.dateParser', 'SharedServices']
)
.service('varianceService', function () {
var variances = {};
return {
redirect: function (path) {
$location.path(path);
},
getHttpVariances: function (month1, month2) {
var url = "/Home/GetVariances?month_1=";
url += month1;
url += "&month_2="
url += month2;
url += "&forwardBilling=true"
$http.get(url).success(function (data) {
variances = data;
return data;
});
return {};
},
getVariances: function () {
return variances;
}
};
})
.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/MainPage', {
templateUrl: 'mainpage.html',
controller: 'MainPageCtrl'
}).
when('/Variance/:type', {
templateUrl: 'variance.html',
controller: 'VarianceCtrl'
}).
otherwise({
redirectTo: '/MainPage'
});
}])
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', 'varianceService', function ($scope, $http, $location) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
The problems lies in the bracket notation of injecting services in your function..
What you inject in the bracket notation must also be present in the function definition..
e.g.
controller('MyCtrl', ['$scope', '$http', 'varianceService', function($scope, $http, varianceService) {
}]);
so in relation to your code above.. it should be like this..
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', '$http', '$location', 'varianceService', function ($scope, $http, $location, varianceService) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
just as how you have ordered the injected services in your bracket notation, it must also pertain the same order in your function definition.
Change this
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
to
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])

Categories