将控制器转换为组件

Convert a controller into a component

如何将控制器转换为组件,然后将其作为依赖项包含在另一个组件中?

我想这样做是为了能够在具有独立范围的组件中使用此控制器中的某些功能。

我的控制器:

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


}]);

$scope替换为'this'对象:

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

});

并在组件中实例化:

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

组件使用 controllerAs 属性 和默认值 $ctrl.

实例化它们的控制器

有关详细信息,请参阅 AngularJS Developer Guide - Understanding Components