我需要在控制器之間共享數據。我在這個例子中發現的Passing data between controllers in Angular JS? &後發現了一個答案。 當導航到 「檔案」 視圖我得到:TypeError:在控制器之間共享數據時,carsService.getCars不是功能
控制器
angular.module('myApp', [
'ngRoute',
'myApp.cars',
'myApp.profile',
'myApp.home',
'myApp.login',
'myApp.version'
]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.otherwise({
redirectTo: '/home'
});
}])
.
service('carsService', function() {
var carList = [];
var addUserCar = function(newObj) {
carList.push(newObj);
console.log("Car Added")
};
var getCars = function(){
return carList;
};
return {
addUserCar: addUserCar,
getCars: getCars
};
});
汽車視圖
<ul class="cars">
<li ng-repeat="car in cars">
<div class="car">
<div class="carView" href="car/{{car.id}}">
<div class="imageView">
<img alt="{{car.name}}" ng-src="{{car.image}}" />
</div>
<div class="carText">
<p>{{car.title}}</p>
<p>{{car.color}}</p>
<p>{{car.description}}</p>
</div>
</div>
<button class="addBtn" ng-click="addUserCar(car.id)">Add car</button>
</div>
</li>
</ul>
「類型錯誤控制器之間共享數據時carsService.getCars不是一個函數」
汽車控制器
.controller('carsCtrl', ['$scope', '$http', function ($scope, $http, carsService) {
$http.get('views/cars.json')
.success(function (data) {
$scope.cars = data;
$scope.addCar = function(currId){
carsService.addUserCar(currId);
};
})
.error(function() {
alert("can not get data from cars.json")
});
}]);
檔案控制器
.controller('profileCtrl', ['$scope', '$http', function ($scope, carsService) {
$scope.userCars = carsService.getCars();
}]);
謝謝,@ ste2425。 提出了另一個問題。當點擊「添加汽車」按鈕時,我看到「TypeError:無法在控制檯 – wrath1888
中讀取未定義屬性'addUserCar'沒問題。這是同樣的問題。在您的其他控制器中,您將包含範圍,http和自定義服務,但是在您的陣列中只包含scope&http。該數組需要匹配按samr順序傳入您的控制器函數的服務。 – ste2425