Angular Extend

Using Angular extend for reusable code/inheritance

by Jeremy Likness

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://code.angularjs.org/1.2.9/angular.min.js"></script>
<div ng-app="exampleApp" ng-controller="exampleCtrl as ctrl">
    <h1>Categories <button ng-if='ctrl.categories.length === 0' ng-click='ctrl.getCategories()'>Load</button></h1>
    <ul>
        <li ng-repeat='category in ctrl.categories'><b>{{category.Name}}</b></li>
    </ul>
    <h1>Products <button ng-if='ctrl.products.length === 0' ng-click='ctrl.getProducts()'>Load</button></h1>
    <ul>
        <li ng-repeat='product in ctrl.products'><b>{{product.Name}}</b> &mdash; {{product.Description}}</li>
    </ul>    
</div>

JavaScript

(function (app) {

    var baseOData = {
        $http: {},
        $q: {},
        baseUrl: 'http://services.odata.org/V4/OData/OData.svc/',
        entity: '',
        get: function () {
            var defer = this.$q.defer();
            this.$http.get(this.baseUrl + this.entity)
                .success(function (response) {
                defer.resolve(response.value);
            })
                .error(function (err) {
                defer.reject(err);
            });
            return defer.promise;
        }
    };
    
    function ProductsService($http, $q) {
        this.$http = $http;
        this.$q = $q;
        this.entity = 'Products';       
    }

    angular.extend(ProductsService.prototype, baseOData);

    app.service('products', ProductsService);

    function CategoriesService($http, $q) {
        this.$http = $http;
        this.$q = $q;
        this.entity = 'Categories';
    }

    angular.extend(CategoriesService.prototype, baseOData);

    app.service('categories', CategoriesService);

    function Controller(products, categories) {
        this.productService = products;
        this.categoryService = categories;
    }
    
    angular.extend(Controller.prototype, {
        products: [],
        categories: [],
        getCategories: function () {
            var _this = this;
            this.categoryService.get().then(function (result) {
                _this.categories = result;
            });        
        }, 
        getProducts: function () {
            var _this = this;
            this.productService.get().then(function (result) {
                _this.products = result;
            });
        }
    });

    app.controller('exampleCtrl', Controller);

})(angular.module("exampleApp", []));