I have a an app.js files which looks something like this:
var app = angular.module('myApp', [$http]);
app.controller('httpController', function($http) {
$scope.httpCommand = function ($http) {
//http stuff in here
};
});
});
I am confused of where to inject dependencies. For example I need $http. Where would I inject this, in the app, controller, or the function itself?
The $http dependency is already declared in your controller constructor. The angular injector service will then pass you the $http instance. The preferred way to declare dependencies however is to use the inline array annotation, which will prevent conflicts found when you minify / compress your javascript files. Angular documentation here. Example:
var app = angular.module('myApp', [$http]);
app.controller('httpController',['$http', function($http) {
$scope.httpCommand = function () {
//http stuff in here,
$http.get("www.someurl.com", function(result) {
//do something with result
});
};
}]);
});
Related
I'm currently attempting to implement Browserify over an existing application.
I have a requirement where I have a BaseService that contains a bunch of standard functionality e.g. setting standard headers on requests etc.
In my factories I use loadash to extend the BaseService. For this to work I need to have a reference to BaseService in any factory that tries to extend it. I can't figure out how to pass through this dependency now I have started to use browserify.
I've added sample code below.
Module declaration:
'use strict';
var angular = require('angular');
module.exports = angular.module('todoApp.services', [require('../secure').name])
.factory('AuthService', ['$q', 'ConsumerConfig', require('./auth-service')])
.factory('BaseWebService', ['$http', '$q', 'Encryption', 'nativeCrypto', require('./base-web-service')]);
AuthService:
'use strict';
var _ = require('lodash');
module.exports = function($q, ConsumerConfig) {
return _.extend({
config: ConsumerConfig,
authenticate: function (options) {
var deferred = $q.defer();
this.callService({
user: options.user,
url: "/AuthenticateUser",
type: "GET"
}).then(function (response) {
deferred.resolve(response.data.userAuthResponse.responseMessage.Token);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
}, BaseWebService);
};
I would ideally like to use DI to inject the dependency but when I try this I keep getting an unknown provider error. Does anyone know how I can get this working?
For anyone looking - I solved this by creating a new "Core" module and then having my services module require the core module.
This way everything was loaded in the correct order
I am working on an angular project and I am using $ resource for the first time. I currently have just as a test to get data out of my database a service that has one call to $resource
Here is my service:
(function() {
"use strict";
angular.module("commonServices")
.factory("ptaResource",
["$resource", ptaResource]);
function ptaResource($resource) {
return $resource("http://localhost:55928/api/excercises", {}, { 'query': { method: 'GET', isArray: true } });
}
})();
My question is this. I have a lot of calls to make to various controllers and methods within those controllers. I cant wrap my head around how to structure a service that allows me to call it with an endpoint listed
I tried doing something like this:
var services =[
getExercises: getExercises,
doSomething: doSomething
];
return service;
function getExercises (){
return $resource request here
}
But that did not work, I have looked on line but any tutorial is only exposing one of each type of request. I am going to have several get requests to controllers, some with different query strings. I will be querying different controllers as well. The purist in me tells me that all of this belongs in one place.
What would be a good method for doing this one large service with a way to call each request individually. Should I break them into a service per web api controller. Any input would be appreciated.
Thanks,
John
If you wanted to wrap your resources in a service, you could do something like this:
angular
.module('commonServices', ['ngResource'])
.factory('ptaResource', ['$resource', function($resource) {
return $resource('http://localhost:55928/api/excercises/:excerciseId', {
excerciseId: '#id'
});
}])
.service('CommonService', ['ptaResource', function(ptaResource) {
return {
getExercises: function() {
return ptaResource.query().$promise;
}
};
}]);
Then you could call it like so:
angular
.module('app', ['commonServices'])
.controller('SomeController', ['$scope', 'CommonService', function($scope, CommonService) {
$scope.exercises = CommonService.getExercises();
// or
CommonService.getExercises().then(function(exercises) {
$scope.exercises = exercises;
}).catch(function(err) {
// handle error here
});
}]);
Whenever I do this:
app.controller('hangmanController', ['$scope', 'wordnickAPIService', function ($scope, wordnickAPIService) {
I get this:
[$injector:unpr] Unknown provider: wordnickAPIServiceProvider <- wordnickAPIService
I read through This discussion on the topic, but didn't see an answer that applied. I am sure it is something simple or trivial that I am missing, but, jeez, if Angular isn't giving me fits trying to piece it all together.
Relevant HTML:
<body ng-app="angularHangmanApp" ng-controller="hangmanController">
My controller:
'use strict';
var app = angular.module('angularHangmanApp', []);
app.controller('hangmanController', ['$scope', 'wordnickAPIService', function ($scope, wordnickAPIService) {
[...]variable declarations[...]
var wordListURL = 'http://long_url_that_returns_some_json';
$scope.wordList = wordnickAPIService.get(wordListURL);
}]);
My factory:
'use strict';
var app = angular.module('angularHangmanApp', []);
app.factory('wordnickAPIService', ['$http', function($http) {
return {
get: function(url) {
return $http.get(url);
},
post: function(url) {
return $http.post(url);
},
};
}]);
The problem is that you are creating multiple modules with the same name.
To create a module in angular you use:
var app = angular.module('angularHangmanApp', []);
Then to get That module somewhere else you just type:
var app = angular.module('angularHangmanApp');
No extra []...
Also make sure you declare the service before trying to call it.
In your factory and your controller, you are actually redefining the app module.
Instead of saying
var app = angular.module('angularHangmanApp', []);
say
var app = angular.module('angularHangmanApp');
Use the first style of invocation only once in your application (maybe just app.js). All other references should use the second style invocation, otherwise, you're constantly redefining the angular app and losing all of the controllers, factories, directives declared previously.
I've been using angularJS for a while now, and I was wondering if it is correct to use the DI this way. Let's say I want to define a service, which needs some angular services. I would probably write the following:
var app = angular.module('myapp', []);
app.service('myService', function($q, $http) {
// Do stuff
});
Is it correct if I write this instead:
var app = angular.module('myapp', []);
app.service('myService', function($injector) {
// DI
var $q = $injector.get('$q');
var $http = $injector.get('$http');
});
I find it clearer and easier to add / remove dependencies.
Thanks for the heads up :-)
It is correct in both ways, for me i prefer to use the first example, because you can inject the dependencies more fast, and in a similar way as you 'inject' modules between your same modules.
I have an angular app that i am developing tests for. In the app.js file i have something like this:
angular.module('app',
[
'app.config',
'app.factories',
'app.directives',
'app.controllers'
]
);
For each controller i want to be in that controller module i essentially define them like this:
angular.module('app.controllers').controller("controller1" ,[],function(){
bleh bleh bleh
code code code
})
The goal here is to write some unit tests with karma but unfortunately the most i have been able to figure out how to do is make sure the dependencies of my main modules load.
What I need to figure out is using the structure i have, how do I (a) create a test to make sure that my controller is actually there, and (b) test things inside the controller
I have tried multiple ways but cannot seem to instantiate the controller within my test framework.
You can test for the existence of your controller like this:
describe("SomeControllerTest", function () {
var scope, ctrl;
beforeEach(module('myApp'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('SomeController', {
$scope: scope
});
}));
it("should be defined", function () {
expect(ctrl).toBeDefined();
});
});
Careful with your controller syntax. The second param is an array of strings ending with the function, the function is not a 3rd param.
app.controller('MyController', [ '$log', function MyController($log) {} ]);