Search code examples
angularjsangularjs-controllerangularjs-components

Convert a controller into a component


How do I convert a controller into a component and then include it in another component as a dependency?

I would like to do this in order to be able to use certain functions which are in this controller in a component, which has an isolated scope.

My controller:

angular
.module('myApp')
.controller('TaxiesController', ['$scope', '$http', '$location', '$routeParams', '$route', 'dataFactory', '$interval', function($scope, $http, $location, $routeParams, $route, dataFactory, $interval){
    console.log('TaxiesController loaded')
    var cancel = {name: 'Preklic', price: 500}
    $scope.taxies = [];
    $scope.taxi = {};
    $scope.taxi.history = [];

    $scope.getTaxies = () => {
        //console.log('X')
        dataFactory.getTaxies().then(function(response){ //make a get req from this address
            $scope.taxies = response.data; 
        });
    }

    $scope.getTaxi = () => {
        var id = $routeParams.id;
        dataFactory.getTaxi(id).then(function(response){ 
            $scope.taxi = response.data; //to moram uporabit, da dobim taxi
        });
    }

    $scope.removeTaxi = (id) => {
        dataFactory.removeTaxi(id).then(function(response){ 
            //window.location.href='#!'; 
        });
    }

    $scope.getTotal = (taxi) => {
        var total = 0;
        for(var i = 0; i < taxi.history.length; i++){ // deluje tudi z $scope.taxi.history.length
            var rent = taxi.history[i];
            if(rent.price) total += rent.price;
        }
        return total;
    }

    $scope.cancelTaxi = (taxi, id) => {
        console.log('cancelling..')
        taxi.available = true;
        taxi.history.unshift(cancel);
        dataFactory.updateTaxi(id, taxi).then(function(response){ 
        });
    }


}]);

Solution

  • Replace $scope with the 'this' object:

    app.controller('TaxiesController', function(dataFactory){
        console.log('TaxiesController loaded')
        var vm = this;
        vm.taxies = [];
    
        vm.getTaxies = () => {
            //console.log('X')
            dataFactory.getTaxies().then(function(response){ //make a get req from this address
                vm.taxies = response.data; 
            });
        }
    
        //Other functions
    
    });
    

    And instantiate it in the component:

    app.component({
        controller: 'TaxiesController',
        template: `
            <button ng-click="$ctrl.getTaxies()">Get Taxies</button>
            <div ng-repeat="taxi in $ctrl.taxies">
                 {{taxi | json }}
            </div>
        `
    }); 
    

    Components instantiate their controllers using the controllerAs property with the default value of $ctrl.

    For more information, see AngularJS Developer Guide - Understanding Components.