Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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){ 
        });
    }


}]);
like image 847
Vid Avatar asked Jun 11 '26 01:06

Vid


1 Answers

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.

like image 55
georgeawg Avatar answered Jun 14 '26 04:06

georgeawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!