w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Angularjs - Declaring factory with a single object with a nested array - getting ReferenceError: .... is not defined
You might want to read this Angular Service Defination: server or factory This isn't a problem of AngularJS but something you're doing wrong in JavaScript. var yourobj = {...} return { addToArray : function() { /* now yourobj is visible */ } in any case, I made a jsfiddle with your code. your "this" makes it visible but a nicer approach is the reveal pattern http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Categories : Angularjs

Abstract factory method; changing the factory passed to an object
Your problem is here: //the DrinkingMethod in the VobFactory class gives us different output data.BoozeFactory = new VobFactory(); //this is what's causing problems data.BoozeFactory.CreateWhiskey(); data.Whiskey.DrinkingMethod(); You never assign the new whiskey to the data.Whiskey property, you create it and then discard it instantly. You should be writing your second line as this: data.Whiskey = data.BoozeFactory.CreateWhiskey(); Or, better yet, have the drinker have a method that does this for it.

Categories : C#

Factory method, why we use a static call to get the object from factory
You have to ask yourself: Will different objects of Factory class behave differently? In this case, will they create new objects in a different manner? The answer is No. If a method is not object scoped, its a perfect candidate for static.

Categories : Java

Setting and retrieving custom object in $routeParams in AngularJS
Changes to the $location service represent a change to the browser address bar so they are string based. So basically there are 2 options: You convert your object to an url compatible string and pass it in the url You store your object in a data container (e.g. scope or rootScope), change your location and then fetch the data again from the data container. The second option is definitely more reliable but technically the first option is valid so it's worth mentioning. Hope that helps!

Categories : Javascript

Generic Key Pool Factory setting parameters
You would be using constructor args. Here's an example lifted from Spring docs: <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg> <constructor-arg><ref bean="yetAnotherBean"/></constructor-arg> <constructor-arg type="int"><value>1</value></constructor-arg> </bean>

Categories : Java

angularjs factory structure for several methods
ok did something like this: myApp.factory('inputinfo', function () { return function (in) { var self = { test: function () { return "hello " + in; }, test2: function () { return "hello " + in; } }; return self; } } And then i could call it like: var test = inputinfo("dude"); alert(test.test()); that would give me the result: hello dude

Categories : Javascript

How call ajax from factory in angularjs?
You should use Angulars' $http for making these calls. Ie. var app = angular.module('myApp', []).config(/* config stuff */ ); app.PersonFactory = angular.factory('PersonResource', function($http) { /* your code here */ /* when you want to make Ajax calls, use $http */ $http.get('/some/url/to/persons') .success(function (response) {...}) .error(function(err){...}); /* keep going */ }); Additionally, if your Persons resource is RESTful, you can just use $resource, ie. var app = angular.module('myApp', []).... /* setup app */ app.personsFactory = angular.factory('personsFactory', function($resource) { var persons = $resource('/api/persons/:id', {id: '@id'}); return persons; }); That way angular will know that on your /api/persons url it can GET persons, it can PO

Categories : Jquery

AngularJS : From a factory, how can I call another function
By doing templates = this.getTemplates(); you are referring to an object property that is not yet instantiated. Instead you can gradually populate the object: .factory('templateFactory', ['$http', function($http) { var templates = []; var obj = {}; obj.getTemplates = function(){ $http.get('../api/index.php/path/templates.json') .success ( function (data) { templates = data; }); return templates; } obj.delete = function (id) { $http.delete('../api/index.php/path/templates/' + id + '.json') .success(function() { templates = obj.getTemplates(); }); } return obj; }]);

Categories : Function

AngularJS $timeout within a resource factory
I think your code looks good. It got to be something else. I simplified a bit and you can see it on the demo. it simulates the http call every half second and the cancelTimes will be called in 4 seconds. app = angular.module('app', []); app.factory('Approvals', ['$timeout', function ($timeout) { var resource = {}; resource.approvalsCount = 0; var approvalsCountTimer; resource.getApprovalsCount = function (username) { console.log(approvalsCountTimer); approvalsCountTimer = $timeout(resource.getApprovalsCount, 500); }; resource.cancelTimers = function () { console.log("stopped"); $timeout.cancel(approvalsCountTimer); }; return resource; }]); function Ctrl($scope, $timeout, Approvals) { Approvals.getApprovalsCount();

Categories : Angularjs

Angularjs resource factory transformResponse is not called
transformResponse is not a parameter to $resource. The response interceptor are configured on $httpProvider. See the documentation of $http (Section Response Interceptor). Keep in mind that once configured these interceptors would run for each request that was made by $http.

Categories : Javascript

Accessing factory defined in another module in angularjs
You need to inject MyServiceModuleTwo into MyServiceModule: var myModuleTwo= angular.module('MyServiceModuleTwo',[]); var myModule= angular.module('MyServiceModuleOne', ['MyServiceModuleTwo']); Then inject notifytwo into notify: myModule.factory('notify', function(notifytwo) { return { sampleFun: function() { notifytwo.sampleFunTwo(); } }; }); myModuleTwo.factory('notifytwo', function() { return { sampleFunTwo: function() { alert('From notify two'); } }; }); And the code on plunker

Categories : Javascript

AngularJS: factory $http.get JSON file
Okay, here's a list of things to look into: 1) If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See: http://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder). 2) The success function returned from $http.get() already splits up the result object for you: $http({method: 'GET', url: '/someUrl'}).success(function(data, status, headers, config) { So it's redundant to call success with function(response) and return response.data. 3) The success function does not return the

Categories : Json

How do I test Angularjs factory stubbing $http?
The $httpBackend.flush() method works only for requests expectations like expectGET. The whenGET method allows you to mock the backend and hijack the request to respond something special but it's doesn't count for the flush. If you call flush() without expectations, it throws the error you're encountering.

Categories : Http

AngularJS : controlling services data with factory
To not have to manually set the data in the 'factory' (aka angular service), you can just set it in the callback to the resource: return { getData: function(id){ return Service.query({id: id}, function(data){ myData = data; }); }, If you want to not deal with the promise object, you can send in a callback of your own to the getData function and when it is complete, call the callback you send in in the callback of the resource: return { getData: function(id, cb){ return Service.query({id: id}, function(data){ myData = data; if (cb) {cb(data);} }); }, Which changes the way you call getData to this: var items =

Categories : Angularjs

How to handle factory service errors in AngularJS
It looks like you want the results function to take callbacks, but its arguments list is currently empty. You are returning the promis though. So either change the call in the controller to: abcFactory.results() .success(function() { ... }) .error(function() { ... }) Or change the results function itself: results: function(successCallback, errorCallback) { var promise = $http(...).success(successCallback).error(errorCallback); return promise; }

Categories : Javascript

where should i use the $http in angularjs? -> difference between factory and service
Services are instantiated, only once, the first time they are called. They're used to share logic and expose data between controllers, for example. Controllers are the glue between the view and the model, like in any MVC framework. Running it at the start of the app or not has nothing to do with doing the $http request from a controller or from a service. Mae the http request when you need it. Notice that controllers are instantiated when angular finds <div ng-controller=whatever>... . If your http request is there, it'll be triggered. There was a similar question about services and factories a few weeks ago and another one about injecting a service in a controller.

Categories : Angularjs

Can't return data from factory to controller AngularJS
Since you are handling the success callback in the controller, make your service function return a promise: temp.SimList = function (){ return $http.get("http://localhost:8080/RetireesClub_server/rest/sim-cards") };

Categories : Angularjs

How do I return data from a $http.get() inside a factory in angularjs
Use defer: obj.getResponse = function(){ var temp = {}; var defer = $q.defer(); $http.get('hello.php').success(function(data){ alert(data); temp =data; defer.resolve(data); }); return defer.promise; }

Categories : Javascript

How to pass Rails current_user to AngularJS factory API call?
The user should never be sent from the client. You should never trust the client. Your rails app should have a session, and you should store the current user somewhere in the session. (Session is a hash, if you are doing it manually just use a sensible key to store the current user's ID). You do it on logging in, and just retrieve it afterwards. class ApplicationController < ActionController::Base attr_accessor :current_user before_filter :load_current_user # ... private def load_current_user self.current_user = User.find(session[:user_id]) end end And in your controller: def usersubmission @submissions = current_user.submissions @submission = @submissions.find(params[:id]) render json: @submission end If you use Devise or similar it's much easier an

Categories : Javascript

Using angularjs service ($cookies) in factory registered using couchpotato
This is off the top of my head, but something like this define(['app'], function(app) { app.couchPotato.registerFactory(['myFactory', [ '$http', '$cookies', function($http, $cookies) { var factory = {}; factory.registerCookie = function(){ $cookies.message = 'hello'; }; return factory; } ] ]); }); You could also look at this sample https://github.com/afterglowtech/angular-couchPotato/blob/master/samples/components-demo/js/lazy/controllers/myCtrl1.js which injects $scope

Categories : Angularjs

AngularJS factory property isn't being updated in $scope when not using push()
The problem is that your factory replace the reference to Factory.foo. When your scope is initialized, $scope.foo holds a reference to an array (empty). When you call Foo.getDataForFoo, it internally changes the reference to Factory.foo but your scope still hold a reference to the previous array. This is why using push works as it doesn't change the array reference, but the array content. There are a few ways to fix this. Without going in all the different options, the easiest one is to wrap your $scope.foo in a function, returning Factory.foo. This way, Angular will detect a reference change in a digest cycle and will update the view accordingly. app.controller('MainCtrl', function($scope,Foo) { $scope.test = 'running'; $scope.foo = function() { return Foo.foo }; $scope.click = F

Categories : Angularjs

AngularJS resource factory always returns empty response
You need to pass in the id. Something like this: loteManager.controller('LoteCtrl', function InfoCtrl($scope, $routeParams, Lotes) { Lotes.get({id: $routeParams.loteId}, function (response){ console.log(response); }); }); ...assuming you have a route defined something like this: $routeProvider.when('/somepath/:loteId, { templateUrl: 'sometemplate.html', controller: LoteCtrl }); Per the documentation: var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); });

Categories : Javascript

Angularjs injecting $resource into factory for Testing with jasmine
ngResource is defined in the separate module. Please check the documentation http://docs.angularjs.org/api/ngResource In other words you have to include <script src="angular-resource.js"> and add ngResource dependency to MyApp.Factory module - angular.module("MyApp.Factory", ["ngResource"]). ps. in the specs you could surround service name with underscores so that we can locally assign a local variable of the same name as the service. For example: var factory; beforeEach(function () { module("MyApp.Factory"); inject(function (_factory_) { factory = _factory_; }); }); According to angularjs coding standards $ should not be used for naming custom directives.

Categories : Unit Testing

$http.get success in AngularJs can't access factory which called it
app.factory('MyFactory',['$http',function($http){ var obj = {}; obj.state = { collectionOfThings: {} }; obj.getThings = function() { $http.get(url).success(function(data) { obj.state.collectionOfThings = data; }); } return obj; }]);

Categories : Angularjs

how to use factory/service for sharing information between multiple controllers in angularjs?
You can access to $scope with : angular.element(document.getElementById('YourCtrl')).scope(); After, you can init data in all your controllers.

Categories : Http

How to access data in a JSON file using a factory and $http in AngularJS?
I changed the following and it worked. Note the change $scope.samples = data.data; sampleApp.controller('sampleAppController', function ($scope, findSamplesFactory) { findSamplesFactory.getSamples().then(function(data){ $scope.samples = data.data; // I changed this. }); ...Your code as it is... }); Check the [plunker]: http://plnkr.co/edit/sZTme6?p=preview

Categories : Json

Angularjs, search form, factory: Button doesn't work
I got it working by changing the controller like this: app.controller( 'VListCtrl', [ '$scope', 'personlistdto', 'VListLoader', function( $scope, personlistdto, VListLoader ) { $scope.personlistdto = personlistdto; $scope.searchFactory = VListLoader; $scope.search = function( ){ $scope.personlistdto = $scope.searchFactory(); }; } ] ); This way the Factory VListLoader is called.

Categories : Forms

Task.Factory.StartNew (Func, object state) build error
I assume you want this overload: TaskFactory.StartNew<TResult>(Func<Object, TResult>, Object) As you can see, the argument of the Func<Object, TResult> must be Object, not State. You can fix your code as follows: Func<object, bool> userMethod = (state) => { State stateObj = (State)state; bool result = TestMethod(stateObj.num, stateObj.str); taskCompletionSource.SetResult(result); return result; }; Note that your code can be shortened as follows: public static void Main(string[] args) { int num = 5; string str = "Helllllllllllo"; Task<bool> taskObj = Task.Run<bool>(() => TestMethod(num, str)); bool result2 = taskObj.Result; Console.WriteLine("Result: {0}", result2); }

Categories : C#

Cannot create an object using factory
This has actually little to do with Angular. You're returning an Object (as the error says) from the method. You may want to return your Entity function. Consider this example: webApp.controller ('entityCtrl', function ($scope, Entity) { $scope.x = new Entity('1','3343','32434'); }); webApp.factory('Entity',function(){ var Entity = function(id,created,updated){ this._id = id; this._created = created; this._updated = updated; }; Entity.prototype.save = function (){ console.log('save'); }; Entity.prototype.update = function () { console.log('update'); }; Entity.prototype._delete = function () { console.log('delete'); }; return Entity; }); Btw. you may want to watch this video, on how the Object Oriented JS works : http://youtu

Categories : Javascript

Object instantiation with a Factory Method
Factory methods are nice as they can return a reference to an object that isn't necessarily an instance of that class. It can return that class, a subtype, or even null, and generally carry themselves on any way they want that a method can. You can thus move logic of selecting types into your own code. You can return an existing instance where appropriate, saving heap space and such. Another basic pseudoexample is Integer.forValue() that can intern an integer, so identical immutable objects don't get recreated for no reason. Also see Executors.newXxxThreadPool(). A basic example: public class Tester { private String name; private int age; // Parameterized constructor private Tester(String myName, int myAge) { this.name = myName; this.age = myAge;

Categories : Java

Accessing an angular factory object without DI
I'm not sure I understand 100% what you want to achieve, but if I'm not mistaken you want to get a hold of the factory object "outside" of the angular context. var factoryObject = angular.injector(['nameOfYourModule']).get('factoryname');

Categories : Angularjs

Check Constraints in Object Constructor or Factory?
As stated in the comments it would be much better to keep validation specific to the domain object. In that way you keep your factory free of the clutter of all of the context specific validation rules. If you want to centralize error handling for the factory just have each of the classes that the factory creates throw an exception on an attempt to create an object that does not match the validation requirements. The your factory can catch and deal with them.

Categories : PHP

Angular js returning undefined object from factory
You need to either use a callback function or just put a return before $http.get... return $http.get('http://example.com/list').then(function (response) { if (response.data.error) { return null; } else { console.log(response.data); return response.data; } });

Categories : Ajax

AngularJS: textarea bind to JSON object shows "object-object"
You can do that in two steps : Create a filter that'll stringify JSON (http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters) $scope.watch the field to save it when it changes (example http://jsfiddle.net/ceJ4w/)

Categories : Angularjs

Jasmine testing with AngularJS, Object [object Object] has no method apply
Clearly LoginController is not defined in the jasmine's specs scope. You should define you controller inside the application's module: angular.module("myApp, []).controller("LoginController", function($scope) {}); ..and instantiate it inside the spec with $controller("LoginController", {}).

Categories : Javascript

Windsor Castle object factory "GetByName" injecting properties
Once again Typed factory is the solution.

Categories : C#

Designing a factory framework with Guice, enumerations, and static factory methods
You've got two problems here, really: How to give Guice the input needed to decide what kind of object to make How to get Guice to run the code to make the right object Problem 1. Guice really really wants to just make a big graph of objects on startup using information provided at startup-time. Yet a lot of what makes it powerful comes from giving it the ability to vary its behavior depending on conditions at runtime - so a lot of frameworks that build on Guice do things to enable that - Servlet support has its request scope which lets a servlet request be injected, and so forth. There are three basic ways to give objects created on-the-fly to Guice to use when creating objects: Assisted Inject Custom scopes Write a one-off Provider<Animal> which gets hold of the relevant d

Categories : Java

django factory boy factory with OneToOne relationship and related field
I believe this is because you have a circular reference in your factory definitions. Try removing the line account = factory.RelatedFactory(AccountFactory) from the UserFactory definition. If you are always going to invoke the account creation through AccountFactory, then you shouldn't need this line. Also, you may consider attaching a sequence to the name field, so that if you ever do need more than one account, it'll generate them automatically. Change: username = "bob" to username = factory.Sequence(lambda n : "bob {}".format(n)) and your users will be named "bob 1", "bob 2", etc.

Categories : Python

GWT Request Factory - Create and persist object - Should proxy automatically be populated with id?
Yes, you are right, calling persist() does not change the proxy object in the client, you have to go to the server to get the object again. The normal way is to define a persistAndReturnSelf() method in your Request. request.persistAndReturnSelf(myTestObj).fire(new Receiver<TestProxy>()) { ... }

Categories : Java

In android examples, why ScreenSlidePageFragment class uses a factory method for creating object
What is wrong with doing what you propose is that the data will be lost on a configuration change. The arguments Bundle is automatically part of the saved instance state of the fragment, and so that data will automatically be retained on a configuration change. Otherwise, by default, you would lose your page number when the user rotates the screen or does any other configuration change. There are other ways that you could address the problem (e.g., put the page number in the onSavedInstanceState() Bundle yourself). The factory method and arguments Bundle is just a simple and effective way of addressing the issue, but it is not the only way.

Categories : Android



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.