Rectangle 27 8

You can do this with a custom filter:

$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
    if (isTrue)
    {
        return Json(new { Foo = "Bar" });
    }
    throw new HttpException(404, "Oh noes...");
}

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        var statusCode = new HttpException(null, exception).GetHttpCode();

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
            Data = new
            {
                error = true,
                message = filterContext.Exception.Message
            }
        };

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = statusCode;  
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

ASP.NET MVC Ajax Error returning view instead of ajax - Stack Overflow

ajax asp.net-mvc jquery error-handling
Rectangle 27 8

You can do this with a custom filter:

$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
    if (isTrue)
    {
        return Json(new { Foo = "Bar" });
    }
    throw new HttpException(404, "Oh noes...");
}

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        var statusCode = new HttpException(null, exception).GetHttpCode();

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
            Data = new
            {
                error = true,
                message = filterContext.Exception.Message
            }
        };

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = statusCode;  
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

ASP.NET MVC Ajax Error returning view instead of ajax - Stack Overflow

ajax asp.net-mvc jquery error-handling
Rectangle 27 4

You can achieve that with a custom filter:

The code for the standard select filter on ngtable says:

<select ng-options="data.id as data.title for data in column.data"
    ng-model="params.filter()[name]"
    ng-show="filter == 'select'"
    class="filter filter-select form-control" name="{{column.filterName}}">
</select>

When you call this data you pass: filter-data="names($column)" and ngtable takes care of getting the data for you. I don't know why this does not work with an external resource. I bet it has something to do with the $column and the promise, as you pointed out.

<select id="filterTest" class="form-control" 
    ng-model="tableParams.filter()['test']" 
    ng-options="e.id as e.title for e in externaldata">
</select>

You fetch this externaldata in your controller:

$scope.externaldata = Api.query(); // Your custom api call

It works perfectly, but I do have an id on my data, so no need of the name function.

Can you please help me with a similar question here?

javascript - How to populate select filters on ng-table from async cal...

javascript angularjs ngtable
Rectangle 27 4

You can achieve that with a custom filter:

The code for the standard select filter on ngtable says:

<select ng-options="data.id as data.title for data in column.data"
    ng-model="params.filter()[name]"
    ng-show="filter == 'select'"
    class="filter filter-select form-control" name="{{column.filterName}}">
</select>

When you call this data you pass: filter-data="names($column)" and ngtable takes care of getting the data for you. I don't know why this does not work with an external resource. I bet it has something to do with the $column and the promise, as you pointed out.

<select id="filterTest" class="form-control" 
    ng-model="tableParams.filter()['test']" 
    ng-options="e.id as e.title for e in externaldata">
</select>

You fetch this externaldata in your controller:

$scope.externaldata = Api.query(); // Your custom api call

It works perfectly, but I do have an id on my data, so no need of the name function.

Can you please help me with a similar question here?

javascript - How to populate select filters on ng-table from async cal...

javascript angularjs ngtable
Rectangle 27 2

In our case it turned out that the error happened because we have a custom filter in our application which does HttpServletResponse sendRedirect() to other url.

For some reason, the redirection is not closing the keep-alive status of the connection, hence the timeout exception.

We checked with Tomcat Docs and when we disabled the maxKeepAliveRequests by setting it's value to 1 and the error stopped showing up.

For now we do not have the actual solution to the error.

java - Tomcat 7.0.43 "INFO: Error parsing HTTP request header" - Stack...

java tomcat servlets tomcat7
Rectangle 27 16

Here is the implementation of custom filter, which will filter the data using array of values.It will support multiple key object with both array and single value of keys. As mentioned inangularJS API AngularJS filter Doc supports multiple key filter with single value, but below custom filter will support same feature as angularJS and also supports array of values and combination of both array and single value of keys.Please find the code snippet below,

myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
    var filterObj = {
        data:items,
        filteredData:[],
        applyFilter : function(obj,key){
            var fData = [];
            if (this.filteredData.length == 0)
                this.filteredData = this.data;
            if (obj){
                var fObj = {};
                if (!angular.isArray(obj)){
                    fObj[key] = obj;
                    fData = fData.concat($filter('filter')(this.filteredData,fObj));
                } else if (angular.isArray(obj)){
                    if (obj.length > 0){
                        for (var i=0;i<obj.length;i++){
                            if (angular.isDefined(obj[i])){
                                fObj[key] = obj[i];
                                fData = fData.concat($filter('filter')(this.filteredData,fObj));    
                            }
                        }

                    }
                }
                if (fData.length > 0){
                    this.filteredData = fData;
                }
            }
        }
    };
    if (keyObj){
        angular.forEach(keyObj,function(obj,key){
            filterObj.applyFilter(obj,key);
        });
    }
    return filterObj.filteredData;
}
}]);
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

Here is a fiddle example with implementation of above "filterMutiple" custom filter. :::Fiddle Example:::

You seem to have the correct intention but your example doesn't seem to work as expected. The output in the table seems rather inconsistent.

This does not work with JSON's with nested objects. Would've been ideal if it did. also it fires a length property undefined error in the console.

It is working for me but it returns all the results if it doesn't find the searched attribute in the list, how can I do to invert this behavior and return no result if the value doesn't exist in the list?

if (fData.length > 0){      this.filteredData = fData; }
this.filteredData = fData;

javascript - How to filter multiple values (OR operation) in angularJS...

javascript angularjs angularjs-ng-repeat
Rectangle 27 16

Here is the implementation of custom filter, which will filter the data using array of values.It will support multiple key object with both array and single value of keys. As mentioned inangularJS API AngularJS filter Doc supports multiple key filter with single value, but below custom filter will support same feature as angularJS and also supports array of values and combination of both array and single value of keys.Please find the code snippet below,

myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
    var filterObj = {
        data:items,
        filteredData:[],
        applyFilter : function(obj,key){
            var fData = [];
            if (this.filteredData.length == 0)
                this.filteredData = this.data;
            if (obj){
                var fObj = {};
                if (!angular.isArray(obj)){
                    fObj[key] = obj;
                    fData = fData.concat($filter('filter')(this.filteredData,fObj));
                } else if (angular.isArray(obj)){
                    if (obj.length > 0){
                        for (var i=0;i<obj.length;i++){
                            if (angular.isDefined(obj[i])){
                                fObj[key] = obj[i];
                                fData = fData.concat($filter('filter')(this.filteredData,fObj));    
                            }
                        }

                    }
                }
                if (fData.length > 0){
                    this.filteredData = fData;
                }
            }
        }
    };
    if (keyObj){
        angular.forEach(keyObj,function(obj,key){
            filterObj.applyFilter(obj,key);
        });
    }
    return filterObj.filteredData;
}
}]);
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

Here is a fiddle example with implementation of above "filterMutiple" custom filter. :::Fiddle Example:::

You seem to have the correct intention but your example doesn't seem to work as expected. The output in the table seems rather inconsistent.

This does not work with JSON's with nested objects. Would've been ideal if it did. also it fires a length property undefined error in the console.

It is working for me but it returns all the results if it doesn't find the searched attribute in the list, how can I do to invert this behavior and return no result if the value doesn't exist in the list?

if (fData.length > 0){      this.filteredData = fData; }
this.filteredData = fData;

javascript - How to filter multiple values (OR operation) in angularJS...

javascript angularjs angularjs-ng-repeat
Rectangle 27 9

You will need to write a custom filter on server side to filter the results. What you type in the box is saved in 'term' and then 'q' is sent as a request parameter with the ajax call. So the ajax call to url:"/concepts/names_for_search?q=deri" should only return the filtered results and not all the results.

Update Select2 will make an AJAX call every time you type in the search box. You have to filter the results on server side and then return the results based on the text in search box. I am using it in my JSP/Servlet application as below

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
{
    String searchTerm = request.getParameter("q");

    String json = getOptions(searchTerm);
    //getOptions method will return a string of  in JSON format
    //[{"id":"1","name":"Derivatives"}]
    response.getWriter().write(json);
}

I found Select2 is used here. If you open the link http://www.indiewebseries.com/search?q=ind and http://www.indiewebseries.com/search?q=in the results obtained are different and based on the 'q' parameter. While in you case, the results for calls to url '/concepts/names_for_search?q=d' and '/concepts/names_for_search?q=deri' are the same(i.e. not filtered)

Hey Thanks and sorry this response is so late. Is there any way to just re-use their filter as if I weren't doing AJAX (maybe copy/pasting from their source code)? Also, do you know of any examples you could point me to? Light-googling has turned up surprisingly little. Thanks a lot for your help - once I am able to upvote people, you'll definitely get one.

@MichaelNomitch - I have updated the answer. Hope this helps.

Select2 Ajax not filtering results based on query - Stack Overflow

jquery-select2
Rectangle 27 2

The idea is to add the above custom filter in the Spring Security filter chain. The order in the filter chain is crucial. Our filter should intercept the session timeout for Ajax calls before the vanilla ExceptionTranslationFilter in order to send the custom HTTP error code.

<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER"/>
@Bean
public Filter ajaxTimeOutRedirectFilter() {
    AjaxTimeOutRedirectFilter f = new AjaxTimeOutRedirectFilter();
    //f.setCustomSessionExpiredErrorCode(901);
    return f;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterAfter(ajaxTimeOutRedirectFilter(), ExceptionTranslationFilter.class)
        ...
        ...
}

java - Spring security Session Timeout handling for Ajax calls - Stack...

java ajax spring spring-security
Rectangle 27 3

First some technical background information: until the upcoming JSF 2.2, JSF doesn't natively support multipart/form-data requests. So the component library offering the file upload component has to come up with a custom Filter itself. This should properly parse multipart/form-data requests and store all the necessary regular data in the HTTP request parameter map and the uploaded file(s) as request attribute(s). This way JSF can continue using request.getParameter() for regular data the usual way and the component library itself can get the uploaded file(s) as request attribute.

In case of Seam's <s:fileUpload>, you need the org.jboss.seam.web.MultipartFilter to perform the multipart/form-data parsing job. I have never used Seam (nor ICEfaces), but Google shows me that you basically need either this in webapp's web.xml

<filter>
    <filter-name>Seam Multipart Filter</filter-name>
    <filter-class>org.jboss.seam.web.MultipartFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Seam Multipart Filter</filter-name>
    <url-pattern>*.seam</url-pattern>
</filter-mapping>
components.xml
<web:multipart-filter url-pattern="*.seam" />

The ICEfaces component must have a similar Filter configured. The ICEfaces 3.x documentation is lacking (or my Google / icefaces.com search skills are bad), so I can't go in detail about this.

Important to keep in mind is that a HTTP request can be parsed only once (the client will send it only once, not multiple times) and thus you can't use the both multipart/form-data parsers simultaneously on the same request. The one which kicks in after the first one would get an empty request body which isn't parseable into anything sensible. So if you're using a component which is using the latter filter, then you wouldn't get anything in the model. Make sure that you haven't by accident or by experiment configured both.

Thanks for your suggestions - I already tried the Seam Multipart Filter stuff which did not work out, but after your comment I looked deeper into my Filter declarations and found out that disabling the Multipart Filter after adding it at least makes ICEfaces doing something - see Update in question.

To confirm, does your UploadBean really have the method fileUploadListener(FileEntryEvent event)? The exception is telling that this method is missing. Your EL expression is fine btw, the event will be automatically supplied. Given the fact that ICEfaces magically works with Seam's filter disabled, it look much like that it's implicitly and silently registering a file upload filter. If you'd prefer to use Seam's one, you might want to look in the ICEfaces documentation if that filter isn't disableable by some context parameter --so that you could if necessary test the Seam one.

Yes, it does. In all other cases in my app, the events are automatically filled in with the listener call, only the FileEntryEvent doesn't want to...e.g. if I call the listener with a parameter of null, it is called and the above message printed out, so at least the method is available somewhere. I think I'll search ICEfaces for the place where the event is raised and see where it goes to, maybe that will help...

Coming back to your question update about classloading issues; that might explain it. The FileEntryEvent class which is loaded by classloader X is not the same FileEntryEvent class which is loaded by classloader Y. It's very reasonable that EL has created the FileEntryEvent argument through classloader X and the managed bean class with the upload method is been loaded through classloader Y. This way the method signature will never match. Front-end libraries (ICEfaces/Seam/etc) doesn't belong in EAR/lib and must be in WEB-INF/lib. So if you fix that part, the upload will likely work.

In other words, you should not have duplicates of the same library in different places of the classpath. You mentioned that it didn't deploy when you remove it from EAR/lib. Do you get a concrete exception/error?

jsf - ICEfaces/Seam file upload component not uploading files - Stack ...

jsf jsf-2 seam icefaces
Rectangle 27 5

You probably want to have a custom authorization filter. Here's an example: Custom filters in MVC. You can then apply this filter globally on app start (using RegisterGlobalFilters).

public class LegacyAuthorize : AuthorizeAttribute
{
  public override void OnAuthorization(HttpActionContext actionContext)
  {
    if (HttpContext.Current.Session["User"] == null)
      base.HandleUnauthorizedRequest(actionContext);
  }
}

Then in your global.asax you'd have something like this:

GlobalFilters.Filters.Add(new LegacyAuthorize());

Overriding the Authorize attribute can be dangerous especially if only validating session. Session Id is not re-generated, which can lead to session hijack via XSS etc. blog.securityps.com/2013/06/ and support.microsoft.com/en-us/kb/899918

c# - Custom Authentication and ASP.NET MVC - Stack Overflow

c# asp.net asp.net-mvc asp.net-mvc-4
Rectangle 27 54

I have just revisited the issue in a real project and finally found a working solution. Proper solution is to have a custom model binder for the type decimal (and decimal? if you're using them):

public class DecimalModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,
                                     ModelBindingContext bindingContext)
    {
        object result = null;

        // Don't do this here!
        // It might do bindingContext.ModelState.AddModelError
        // and there is no RemoveModelError!
        // 
        // result = base.BindModel(controllerContext, bindingContext);

        string modelName = bindingContext.ModelName;
        string attemptedValue =
            bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

        // Depending on CultureInfo, the NumberDecimalSeparator can be "," or "."
        // Both "." and "," should be accepted, but aren't.
        string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
        string alternateSeperator = (wantedSeperator == "," ? "." : ",");

        if (attemptedValue.IndexOf(wantedSeperator) == -1
            && attemptedValue.IndexOf(alternateSeperator) != -1)
        {
            attemptedValue =
                attemptedValue.Replace(alternateSeperator, wantedSeperator);
        }

        try
        {
            if (bindingContext.ModelMetadata.IsNullableValueType
                && string.IsNullOrWhiteSpace(attemptedValue))
            {
                return null;
            }

            result = decimal.Parse(attemptedValue, NumberStyles.Any);
        }
        catch (FormatException e)
        {
            bindingContext.ModelState.AddModelError(modelName, e);
        }

        return result;
    }
}

Then in Global.asax.cs in Application_Start():

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

Note that code is not mine, I actually found it at Kristof Neirynck's blog here. I just edited a few lines and am adding the binder for a specific data type, not replacing the default binder.

I just updated my answer adding an additional check in code to make it properly handle nullable properties. I discovered that if it found an empty string as the attempted value it would throw an exception even if the property being bound is nullable. Now it should work just fine.

There's a complementary client side fix that should be applied along this one. You'll find it here: stackoverflow.com/a/8102159/41420

Didn't work with string as input

You don't need to do this. What you need to do is set the culture of the current thread before the model binder is executed as in this example.

globalization - How to set decimal separators in ASP.NET MVC controlle...

asp.net-mvc globalization
Rectangle 27 3

It will definitely not work the way you want it, as local variable names are not even included in the assembly after it is compiled.

It might be possible if the variable is a field of a class (by passing a FieldInfo instead of the actual value or when the variable is passed ByRef).

c# - How to detect variable *name* (not type) within a function (Why? ...

c# .net asp.net vb.net
Rectangle 27 5

Clean solution that filter successfuly out system apps

The idea behind this solution is that the main activity of every system app does not have a custom activity icon. This method gives me an excellent result:

public static Set<PackageInfo> getInstalledApps(Context ctx) {
    final PackageManager packageManager = ctx.getPackageManager();

    final List<PackageInfo> allInstalledPackages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA);
    final Set<PackageInfo> filteredPackages = new HashSet();

    Drawable defaultActivityIcon = packageManager.getDefaultActivityIcon();

    for(PackageInfo each : allInstalledPackages) {
        if(ctx.getPackageName().equals(each.packageName)) {
            continue;  // skip own app
        }

        try {
            // add only apps with application icon
            Intent intentOfStartActivity = packageManager.getLaunchIntentForPackage(each.packageName);
            if(intentOfStartActivity == null)
                continue;

            Drawable applicationIcon = packageManager.getActivityIcon(intentOfStartActivity);
            if(applicationIcon != null && !defaultActivityIcon.equals(applicationIcon)) {
                filteredPackages.add(each);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.i("MyTag", "Unknown package name " + each.packageName);
        }
    }

    return filteredPackages;
}

How to get a list of installed android applications and pick one to ru...

android android-intent
Rectangle 27 5

Clean solution that filter successfuly out system apps

The idea behind this solution is that the main activity of every system app does not have a custom activity icon. This method gives me an excellent result:

public static Set<PackageInfo> getInstalledApps(Context ctx) {
    final PackageManager packageManager = ctx.getPackageManager();

    final List<PackageInfo> allInstalledPackages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA);
    final Set<PackageInfo> filteredPackages = new HashSet();

    Drawable defaultActivityIcon = packageManager.getDefaultActivityIcon();

    for(PackageInfo each : allInstalledPackages) {
        if(ctx.getPackageName().equals(each.packageName)) {
            continue;  // skip own app
        }

        try {
            // add only apps with application icon
            Intent intentOfStartActivity = packageManager.getLaunchIntentForPackage(each.packageName);
            if(intentOfStartActivity == null)
                continue;

            Drawable applicationIcon = packageManager.getActivityIcon(intentOfStartActivity);
            if(applicationIcon != null && !defaultActivityIcon.equals(applicationIcon)) {
                filteredPackages.add(each);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.i("MyTag", "Unknown package name " + each.packageName);
        }
    }

    return filteredPackages;
}

How to get a list of installed android applications and pick one to ru...

android android-intent
Rectangle 27 5

Clean solution that filter successfuly out system apps

The idea behind this solution is that the main activity of every system app does not have a custom activity icon. This method gives me an excellent result:

public static Set<PackageInfo> getInstalledApps(Context ctx) {
    final PackageManager packageManager = ctx.getPackageManager();

    final List<PackageInfo> allInstalledPackages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA);
    final Set<PackageInfo> filteredPackages = new HashSet();

    Drawable defaultActivityIcon = packageManager.getDefaultActivityIcon();

    for(PackageInfo each : allInstalledPackages) {
        if(ctx.getPackageName().equals(each.packageName)) {
            continue;  // skip own app
        }

        try {
            // add only apps with application icon
            Intent intentOfStartActivity = packageManager.getLaunchIntentForPackage(each.packageName);
            if(intentOfStartActivity == null)
                continue;

            Drawable applicationIcon = packageManager.getActivityIcon(intentOfStartActivity);
            if(applicationIcon != null && !defaultActivityIcon.equals(applicationIcon)) {
                filteredPackages.add(each);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.i("MyTag", "Unknown package name " + each.packageName);
        }
    }

    return filteredPackages;
}

How to get a list of installed android applications and pick one to ru...

android android-intent
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

This might be the best explanation. Sometimes examples are just distracting when you want the real meaning!

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

This might be the best explanation. Sometimes examples are just distracting when you want the real meaning!

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

This might be the best explanation. Sometimes examples are just distracting when you want the real meaning!

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider