2015-12-03 223 views
1

昨天我詢問了控制器之間的數據交換表單。但正確的問題是,我如何在重定向一些視圖之後在控制器之間交換數據。這是一個想法(僞):將數據從一個控制器傳遞到另一個控制器以重定向到視圖

controller1("$scope", function($scope){ 
var val1 = $scope.dataFromview 
href = ("#/search", val1); 
}); 

    controller2("$scope", function($scope, controller1){ 
var val2 = controller1.val1; 

//make something with val2 

}); 

感謝

回答

2

退房http://egghead.io/lessons/angularjs-sharing-data-between-controllers

而且事先張貼在計算器 Passing data between controllers in Angular JS?

你可以定義將被注入到兩個控制器服務:

app.service('exampleService', function() { 

    var val1; 
    var href = "#/search"; 

    var setVal = function(newString) { 
     val1 = newString 
    }; 

    var getVal = function(){ 
     return val1; 
    }; 

    return { 
    setVal: setVal, 
    getVal: getVal 
    }; 


}); 

依賴注入服務到兩個控制器。

在你的第一個控制器,定義一些動作,設置的值:

app.controller('ControllerOne', function($scope, exampleService) { 
    $scope.addValOne = function(newString){ 
     exampleService.setVal(newString); 
    }; 
}); 

在你的第二個控制器,從服務中獲得的VAL1:

app.controller('ControllerTwo', function($scope, exampleService) { 
    $scope.val1 = exampleService.getVal(); 
}); 
+0

出色答卷水平。我會用jsbin來測試。謝謝。 –

+0

我這樣做,但沒有工作: – Alfredo

+0

這是控制器中的方法,從視圖獲取數據 - > $ scope.indexData = function(){var 0; 0; newString = $ scope.searchBox; dataService.setVal(newString); $ window.location.href =「#/ search」; - >這是主要部分,但不會重定向到searh路由... – Alfredo

0

假設我們想與大家分享控制器之間的產品對象。在這裏,我已經創建了一個名爲SharedDataService的AngularJS服務爲顯示在下面的代碼片段:

myApp.service('SharedDataService', function() { 
    var Product = { 
     name: '', 

     price: '' 

    }; 

    return Product; 

}); 

接下來讓我們繼續前進,並使用SharedDataService兩個不同的控制器。在控制器中,我們使用上一步中創建的服務。可以創建控制器,如下圖所示:

var myApp = angular.module("myApp", ['CalService']); 



myApp.controller("DataController1", ['$scope', 'SharedDataService', 

    function ($scope, SharedDataService) { 

    $scope.Product = SharedDataService; 



    }]); 



myApp.controller("DataController2", ['$scope', 'SharedDataService', 

    function ($scope, SharedDataService) { 

    $scope.Product = SharedDataService; 



}]); 

在視圖,我們可以簡單地使用控制器,如下圖所示列表:

 <h2>In Controller 1h2> 

     <input type="text" ng-model="Product.name" /> <br/> 

     <input type="text" ng-model="Product.price" /> 

     <h3>Product {{Product.name}} costs {{Product.price}} h3> 

    div> 

    <hr/> 

    <div ng-controller="DataController2"> 

     <h2>In Controller 2h2> 

     <h3>Product {{Product.name}} costs {{Product.price}} h3> 

    div> 
相關問題