I have this factory and I have the error in the title. How can I fix this?
(function (angular,namespace) {
var marketplace = namespace.require('private.marketplace');
angular.factory('blueStripeViewModelFactory', [
'$http', function blueStripeViewModelFactory($http) {
return new BlueStripeViewModel("id", 10);
}
]);
marketplace.blueStripeViewModelFactory = blueStripeViewModelFactory;
})(window.angular,window.namespace);
You can't create an independent factory as it should be created within a module.
Example,
angular.module("myFactoryModule").factory("blueStripeViewModelFactory",function(){
// define your factory
});
Now you are able to use this factory in any of your module. To use this module, you just need to add an injector of your factory module (here, myFactoryModule).
Example,
angular.module("anotherModule", ["myFactoryModule"]);
Related
I am using the controller as syntax from angular and i want to test my code using jasmine and sinon.
Let's say i want the following controller code :
angular
.module('Test')
.controller('TestController', TestController);
TestController.$inject = [];
function TestController() {
var viewModel = this;
viewModel.myFunction = myFunction;
function myFunction(){
//do something
//now call a helper function
helperFunction()
}
function helperFunction(){
// ....
}
}
My question is how i can test the helperFunction() or even put a spy on it ? My helper is not visible in my test.
Here is my test :
(function () {
'use strict';
var myController;
describe('Test', function () {
beforeEach(module('Test'));
beforeEach(inject(function ($controller, $injector) {
myController = $controller('TestController');
}));
it('Tests helperFunction', function (){
var sinonSpy = sinon.spy(myController, 'helperFunction');
//perform the action
myController.myFunction();
//expect the function was called - once
expect(sinonSpy .callCount).toEqual(1);
}
})
})
You cannot have access to those functions. When you define a named JS function it's the same as saying:
var helperFunction = function(){};
In which case it would be pretty clear to see that the var is only in the scope within the block and there is no external reference to it from the wrapping controller.
To make a function testable, you need to add it to the $scope of the controller.
viewModel.helperFunction = helperFunction;
But be aware that is not a good idea to be exposing everything just to make it testable. You really need to consider if testing it will actually add some value to your project
try to do so :
var vm = controller("helperFunction", { $scope: scope });
and then:
vm.myFunction();
Add the following code into your controller:
angular.extend($scope, {
helperFunction:helperFunction
});
I have a service which will return the name of factory. I already injected all the factories into controller. I need to use the variable to call the method inside that factory. I know i can use
if(var == 'factoryname') {
factoryname.method()
}
but i don't want those if conditions because i have number of factories. Is there any way to call a method inside that factory like in java script
window[var]
You should consider storing all of your factories on an object:
var factories = {
factoryA: { method: function() {} },
factoryB: { method: function() {} },
};
var factory = 'factoryA';
factories[factory].method();
I am working on a calculator that will consider AWS instance costs. I am pulling the data from a .js file on amazon and I would like to read it into an object but i keep getting an error "Uncaught ReferenceError: callback is not defined" .. here is my .js file.
(function() {
var app = angular.module('formExample', []);
var ExampleController = function($scope, $http) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
$scope.GetAws();
};
$scope.reset = function() {
$scope.user = "";
};
function callback(data) {
$scope.aws = data;
}
$scope.GetAws = function() {
var url = "http://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js?callback=callback";
$http.jsonp(url);
};
$scope.reset();
};
app.controller('ExampleController', ['$scope', '$http', ExampleController]);
}());
It is weird that the aws link you are using supports jsonp but it does not take custom callback function name. (Atleast you can look up to find out if the query string they are looking for is callback or not). angular handles it when we provide callback=JSON_CALLBACK it gets translated to angular.callbacks_x which are exposed globally temporarily by angular to handle the request and resolve the promise accordingly. But for this the endpoint must take the callback argument and wrap the response in the same string and function invocation. However this endpoint does not seem to consider it and even without any callback it automatically wraps into default callback function invocation. So you would need to inject $window (Correct DI way) object and set callback function to it and ?callback=callback is irrelevant.
var ExampleController = function($scope, $http, $window) {
$scope.master = {};
//....
$window.callback = function(data) {
$scope.aws = data;
}
$scope.GetAws = function() {
var url = "http://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js?callback=callback";
$http.jsonp(url);
};
$scope.reset();
};
app.controller('ExampleController', ['$scope', '$http', '$window', ExampleController]);
Plnkr
It is because the AWS script is looking to call a function called "callback" on the global scope (outside of Angular). Since your function is within the scope of another (IIFE) function, it cannot be accessed.
What I've done in a case like this is simply put the function in the global scope.
In cases where an application requires some API to have loaded before Angular can do it's magic and has a callback similar to your situation, I have done the following, manually bootstrapping Angular:
index.html
<script src="http://www.example.com/api?callback=myCallbackFunction"></script>
app.js
// callback function, in global (window) scope
function myCallbackFunction() {
// manually bootstrap Angular
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
}
// your IIFE
(function() {
})();
Notice callback should be set in window scope.
So,one solution is like:
$scope.reset = function() {
$scope.user = "";
};
window.callback = function(data) {
$scope.aws = data;
}
$scope.GetAws = function() {
var url = "http://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js?callback=callback";
$http.jsonp(url);
};
So I have a tree helper object in my angular app that provides a bunch of useful functions for dealing with the many tree structures in the app. This is provided by a factory, so each time some controller (or whatever) asks for a tree helper, it gets its own copy:
angular.module('MainApp').factory('TreeHelperFactory',
function ($http, $q, $filter, DataService) {
var treeHelper = new function ($http, $q, $filter, DataService) {
...
code
...
})
Now I have a category service that provides various category-related functions, including returning a tree of categories and providing ways to manipulate that tree. So thinking like an OO developer, I reckon that the category service is really like a subclass of my tree helper, so I inject a tree helper instance and then attempt to extend that instance with category-specific functions, naively like this:
angular.module('MainApp').provider('CategoryService',
function() {
this.$get = function ($http, $q, $filter, DataService, TreeHelperFactory) {
var catService = TreeHelperFactory;
catService.listCategories = function() {...}
catService.deleteCategory = function(id) {...}
... more code...
return catService;
}
}
);
But this doesn't work. The new properties are not visible when I try to invoke them later, only the tree helper properties of the original factory object. What am I missing and how do I achieve this?
Services in angular.js are singletons, which means each time you inject a service it returns the exact same object, you cannot force it to return a new object each time it is injected.
What you can do is to create a Class function, for example:
angular.module('MainApp')
.factory('TreeHelperFactory',
function ($http, $q, $filter, DataService) {
/**
* TreeHelper constructor
* #class
*/
function TreeHelper() { /* this.init(); */ }
/**
* TreeHelper static class method
*/
TreeHelper.list = function() { /* ... */ };
/**
* TreeHelper instance method
*/
TreeHelper.prototype.init = function() { /*...*/ };
/**
* Returns the class
*/
return TreeHelper;
})
Now you can inject it, instantiate an object and extend it like so:
.factory('CategoryService', function (TreeHelperFactory) {
var catService = new TreeHelperFactory();
catService.listCategories = function() { /*...*/ };
catService.deleteCategory = function(id) { /*...*/ };
return catService;
});
You can also use javascript prototypical inheritance but I think it's an overkill for most cases so keep it simple if you can.
Helper that depends on Angular services is a bad smell for me - almost like its status is more than a helper and it has a service or two in it. Would you be able to rethink this through restructuring their roles and responsibilities?
I am new to angular world and I have function which is loading the html inside perticular div on load and then controller gets initialize. I want to make single var available inside the controller so wondering if it's possible to assign that var to scope from outside the controller.
//controller
var cntlrs = angular.module('MyModule');
cntlrs.controller('ControllerTest', function ($scope, $http) {
//want to have var available here from $scope
});
//accessing scope from outside
var appElmt = document.querySelector('[ng-app=MyApp]');
var $scope = angular.element(appElmt).scope();
var customer = "New Customer";
//how can I set customer value inside scope?
I would suggest reading the angular docs more. $scope is your model (or probably the term ViewModel is more appropriate).
To get values into your controller, I would recommend a factory or a service. One can call setCustomer on the factory, then other controllers would be able to see that value using getCustomer.
var mod = angular.module('MyModule', []);
mod.factory("CustomerFactory", function () {
var customer;
return {
getCustomer: function () {
return custData;
}
setCustomer: function (custData) {
customer = custData;
}
}
});
mod.controller("TestController", function ($scope, $http, CustomerFactory) {
$scope.customer = CustomerFactory.getCustomer();
}
It might also be better if you weren't referencing $scope outside of angular (i.e. from angular.element(...).scope()). I don't know what you are trying to solve, but it seems like from the code above, all that logic can be put inside the controller.
Yes, from outside the controller you can target an element that is within your angular controller:
var scope = angular.element("#YourElementID").scope();
And now you will have access to everything on the scope (Just as if you were using $scope)
I decided to work like this, and it seems to be allright!! It does not require a big effort, the only boring part is that in the template you need always to use vars.somepropertyormethod
//an outside var that keeps all the vars I want in my scope
var vars = {
val1: 1,
val2: "dsfsdf",
val3: function() {return true;}
}
//and here I set the controller's scope to have ONLY vars and nothing else:
angular.module('myModule', [])
.controller('myControllerOpenToTheWorld', function($scope) {
$scope.vars = vars;
});
With this, I can set vars.anyproperty from anywhere I want. The trick is that the real values are all wrapped inside an object, so as long as you don't reassign the wrapper vars, you can access it from both outside and inside:
//change val2
vars.val2 = "new value changed from outside";
In the markup, it would work like this:
<div>{{vars.val1}}</div>
<div ng-if:"vars.val3()">{{vars.val2}}</div>