【问题标题】:Convert a controller into a component将控制器转换为组件
【发布时间】:2018-07-31 03:32:57
【问题描述】:

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

我想这样做是为了能够在具有隔离作用域的组件中使用此控制器中的某些功能。

我的控制器:

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


}]);

【问题讨论】:

  • 如果其他组件主要是展示性的,我会传入要调用的函数作为其他组件的回调。否则,您可以将功能放在服务中并将其注入其他组件。
  • 我如何将它放入服务中?如果您不能确切地告诉我如何做到这一点,我会请您指点我一个显示它的示例。
  • 你已经有一个叫dataFactory的服务(工厂基本一样)。看看它是如何构建的。

标签: angularjs angularjs-controller angularjs-components


【解决方案1】:

$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

【讨论】:

    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    相关资源
    最近更新 更多