Jeremy Miller Jeremy Miller - 1 month ago 6
AngularJS Question

Angular Service created function needs this keyword

While the question is more I suppose javascript type question more so than an Angular question, I was creating a service in which I would call it like this

// controller injects activityApi , then service function call is made
var activities = activityApi.getActivityById(1122);


I get an error if I do not put "this" keyword in front of function name
1. Why do I need "this."

2. What other alternatives? ( I am trying to get into the habit of not doing old school javascript with
function blah() { ... }


this.getActivityById = function(id) {
$http.get('/Umbraco/Api/ActivityApi/GetActivity').
success(function (data, status, headers, config) {
console.log(data);
return data;
}).
error(function (data, status, headers, config) {
// log error
});
};

Answer

If you are writing a factory make use of an object inside the factory ,and put all your calls into it.like

(function() {
    'use strict';

    angular
        .module('app')
        .factory('activityApi', activityApi);

    activityApi.$inject = ['$http'];

    function activityApi($http) {
        var service = {
              getActivityById : getActivityById ,
        };
        return service;


     function getActivityById (id) {
        $http.get('/Umbraco/Api/ActivityApi/GetActivity').
          success(function (data, status, headers, config) {
           console.log(data);
           return data;
        }).
       error(function (data, status, headers, config) {
          // log error
       });
    };

    };
})();

here you are returning factory object in which calling function is available.

Here you can call the factory function as

var activities = activityApi.getActivityById(1122);