如何将控制器转换为组件,然后将其作为依赖项包含在另一个组件中?
我想这样做是为了能够在组件中使用此控制器中的某些功能,这些功能具有独立的范围。
我的控制器:
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){
});
}
}]);
答案 0 :(得分: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。