This is a noobie question:
I am playing with the Angular seed app and am trying to write a controller but am having no luck getting access to $scope (and any other dependency).
angular.module('myApp.controllers', []).
controller('mainCtrl', [function( $scope, $http ) {
$http.get('config/configuration.json').success( function( data ) {
$scope.gametitles = data.gametitles;
$scope.environments = data.environments;
$scope.playermanagerServer = data.playermanagerServer;
});
$scope.gametitle = $scope.gametitles[0];
$scope.environment = $scope.environments[0];
}])
If I break in the code, both $http and $scope are undefined. How do I get access to these?
Thanks in advance
I think the problem is in the syntax of your controller declaration. Try controller('mainCtrl', ['$scope', '$http', function ($scope, $http) { ... controller code ...}]);
you may want to check A's documentation for dependency injection in controllers here
Or,assuming you're not uglifying your code you could just use simpler injection formation:
controller('mainCtrl', function( $scope, $http ) {} )
(note that the function is not a member of an array, but passed directly)
Related
i'm very much new to angular and trying to access localStorage. Here is the code. Please help me figure that out if it is not the right way to define and use. Thank you.
var app = angular.module("toggleApp", ['LocalStorageModule']).config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('test')
.setStorageType('localStorage');
});
app.controller("toggleController", function ($scope, $timeout,
timerParsingService, localStorageService) {
localStorageService.set('user' ,'yash');
you dont require to define any module or inject any other module in the application.
inject $window in your application and then you can access the localstorage module like this
angular.module('toggleApp', [])
.controller('toggleController', ['$scope', '$window', function ($scope, $window) {
$window.localStorage.setItem('ls', 'test');
}]);
and save the value like this
$window.localStorage.setItem('ls', 'test');
and you can retrieve the localStorage value like this
$window.localStorage.getItem('ls');
you could use ng-storge module and use
$localStorage.key = value or you could also use the getter and setter
$localStorageProvider.set('key', { k: 'value' });
I have the following preloader.js factory file included in my project.
angular.module('movieSeat')
.factory('preloader', function( $q, $rootScope ) {
In my controller I inject the factory as following:
angular.module('movieSeat')
.controller('moviesearchCtrl', ['$scope', 'moviesearchFactory', function ($scope, moviesearchFactory, preloader) {
When I try to use the preloadImages function inside the preload controller:
$scope.imageLocations = [
"https://image.tmdb.org/t/p/w300_and_h450_bestv2//nlqFgG7jfBITl8fJHzL72jXwYLt.jpg",
"https://image.tmdb.org/t/p/w300_and_h450_bestv2//ghL4ub6vwbYShlqCFHpoIRwx2sm.jpg",
"https://image.tmdb.org/t/p/w300_and_h450_bestv2//weUSwMdQIa3NaXVzwUoIIcAi85d.jpg",
];
preloader.preloadImages($scope.imageLocations)
I get the following error:
Cannot read property 'preloadImages' of undefined
If I comment out the preloader.preloadImages($scope.imageLocations) code the error is gone. So to me it looks like injecting the preloader factory in my controller works fine but I can't figure out why I can't call the function preloadImages on the preload factory.
There's a typo in the dependency injection list. You forgot to add preloader in the list of dependency strings.
.controller('moviesearchCtrl', ['$scope', 'moviesearchFactory', 'preloader' /*here*/, function ($scope, moviesearchFactory, preloader) {
You need to reference your factory/service 'preloader' in your controller call as follows:
angular.module('movieSeat')
.controller('moviesearchCtrl', ['$scope', 'moviesearchFactory', 'preloader', function ($scope, moviesearchFactory, preloader) {
})
I am using a service to get data from the server using $http.get() method. I am calling the function in the service and then accessing its variable from the controller. But it is not working this way.
The code is below
'use strict';
var mission_vision_mod = angular.module('myApp.mission_vision', ['ngRoute']);
mission_vision_mod.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/mission_vision', {
templateUrl: 'partials/mission_vision/mission_vision.html',
controller: 'mission_visionCtrl'
});
}]);
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope, $http, getMissionData) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getmissiondata();
$scope.missions = getMissionData.missiondata;
$scope.len = $scope.missions.length;
}]);
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
});
}
}]);
When i write the$http.get() function in the controller itself, it works. I am new to angular JS.
Try writing your service like this
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
this.getMissionData=function(){
return $http.get('m_id.json');
}
}]);
Use Service in controller like this:
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope,getMissionData,$http) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getMissionData().success(function(response){
$scope.missions=response;
$scope.len = $scope.missions.length;
}).error(function(errorl){
//handle error here
});
}]);
Also I suggest using a better name for service -'MissionDataService' :)
EDIT- Your sequence of injected service should match sequence of injectable names specified in the array..See my last edit
['$scope','getMissionData','$http',
function($scope, $http, getMissionData
The service names don't match with the variable names.
My advice: stop using this array notation. It clutters the code and is a frequent source of bugs. Use ng-annotate.
That said, your service is not correctly defined. It doesn't have any member function that would allow it to be called. Re-read the documentation of services. Defining services using factory() is easier than defining them using service(), BTW. And the service should return the promise returned by $http. Trying to access the value returned by an asynchronous call right after making the asynchronous call will never work. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/
Try:
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
return missiondata;
});
}
}]);
I'm new to angular and have the following code.
angular.module('MyApp')
.controller('loginController', ['$scope', '$http', 'conditionalDependency',
function ($scope, $http, conditionalDependency{
}
I would like to have conditionalDependency loaded conditionally. Something like this
if(true)
{
//add conditionalDependency
}
How can this be done. I've seen this post . However, my requirement is that I have the dependency specified in function
Thanks in advance.
Not quite clear as to why you would have to have it in a named function like in your example but...
If you need conditional dependencies, I would suggest taking a look at the following:
Conditional injection of a service in AngularJS
I've used this method in a couple niche scenarios and it works quite well.
EXAMPLE:
angular.module('myApp').controller('loginController',
['$injector', '$scope', '$http',
function($injector, $scope, $http) {
var service;
if (something) {
service = $injector.get('myService');
}
});
You can use it even without injecting injector in your controller
if(something){
var injector = angular.element(document).injector();
var myService = injector.get('myService')
}
Use:
angular.injector().get('conditionalDep');
You can inject $injector once to your file and call $injector.get('dep');
I have a controller that it's not defined on $routeProvider. I use it internally inside other controllers. Is there a way to resolve a dependency without the $routeProvider?
==
My friend below asked for more information, here it goes:
I don't want to call promise methods (basically then) inside my controllers. But I have dependencies on some of this controllers that are promises. When a controller is defined on the $routeProvider, I can resolve its dependencies. But how about the controllers that are not defined there? Is there any solution? Follows an example:
My $routeProvider doesn't map this controller and this is the code I have to do because my Cart is a promise:
.controller('MyCtrl', ['$scope', 'Cart',
function ($scope, Cart) {
Cart.then(function(res) {
$scope.cart = res.query();
});
This is the code I'd like to do:
.controller('MyCtrl', ['$scope', 'Cart',
function ($scope, Cart) {
$scope.cart = Cart.query();
});
if you mean resolve -- dependency injection -- yes. below should work:
element.injector().invoke(['dep1','dep2', function(dep1,dep2){}])
...
the idea is to retrieve the current injector, and use invoke().