簡體   English   中英

使用 AngularJS 從一個控制器獲取數據到另一個控制器

[英]Getting data from one controller to another with AngularJS

我有兩個控制器,並希望它們在不創建工廠的情況下將數據從第一個發送到第二個。

    module.controller('UpdatesController', function ($scope) {
    var update = {};
    update.items = [{
        title: 'Company goes high',
        date: '24-11-2015',
        excerpt: 'Labore et dolore magna aliqua',
        desc: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
        picture: 'images/01.jpg',
    }];
    $scope.items = update.items;
    $scope.showUpdate = function (index) {
            var selectedItem = update.items[index];
            update.selectedItem = selectedItem; 
            $scope.navi.pushPage('update.html', {
                title: selectedItem.title,
                date: selectedItem.date,
                excerpt: selectedItem.excerpt,
                desc: selectedItem.desc,
                picture: selectedItem.picture
            });
        };
});

module.controller('UpdateController', function ($scope, items) {
    $scope.item = items;
});

但它似乎不起作用。 錯誤是:未捕獲(承諾)錯誤:[$injector:unpr]

可以請任何人幫忙嗎?

在 AngularJS 中,一個controller不能注入其他controller 如果您想要控制器之間的互連/共享,那么您應該使用工廠或服務。

在你的情況下,你可以做

 module.controller('UpdatesController', ['$scope', 'TestFactory', function ($scope, TestFactory) {
var update = {};
update.items = [{
    title: 'Company goes high',
    date: '24-11-2015',
    excerpt: 'Labore et dolore magna aliqua',
    desc: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    picture: 'images/01.jpg',
}];
$scope.items = update.items;
TestFactory.setItems($scope.items);
    $scope.showUpdate = function (index) {
            var selectedItem = update.items[index];
            update.selectedItem = selectedItem; 
            $scope.navi.pushPage('update.html', {
                title: selectedItem.title,
                date: selectedItem.date,
                excerpt: selectedItem.excerpt,
                desc: selectedItem.desc,
                picture: selectedItem.picture
            });
        };
}]);

module.controller('UpdateController', ['$scope', 'TestFactory', function ($scope, TestFactory) {
    $scope.item = TestFactory.getItems();
}]);

module.factory('TestFactory', function(){
    return {
      getItems : function(){
        return this.items;
      },
      setItems : function(items){
        return this.items = items;
      }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM