簡體   English   中英

將參數從一個控制器傳遞到另一個AngularJS

[英]Passing params from one controller to another AngularJS

我有一個獲取機場列表的控制器,該控制器提供了一個輸入組件,該組件用於出發,然后再次用於到達。 自動完成組件適用於每種情況。 我試圖弄清楚如何將每個選定的機場輸入作為單個參數傳遞給另一個控制器,該控制器從第二個URL獲取價格。 關於如何使用一個組件執行此操作的任何想法?

這是初始獲取的控制器

 $scope.airport_list = null;

 $http({
  url: 'someUrl.com',
  method: 'GET'
 })
  .then((response) => {
    $scope.airport_list = response.data.airports;
 });

 $scope.searchFor = function(airportName) {
  $scope.hidelist = false;
  const output = [];
  angular.forEach($scope.airport_list, function(airport) {
    if (airport.name.toLowerCase() === airportName) {
      output.push(airport);
    }
  });
  $scope.airports = output;
 };

 $scope.selectAirport = function(airportName) {
   $scope.airportSearch.name = airportName.name;
   $scope.state = !$scope.state;
 };

這是多次使用的單個輸入組件。

<div class="control" ng-controller="selectCtrl">
  <div>
    <input type="text" name="airport" 
      id="airport" ng-model="airportSearch.name" />
      <div class="airport-container-dropdown" ng-
        hide="!airportSearch.name">
      <div class="airport-list"
        ng-repeat="airport in airport_list | filter:airportSearch"
        ng-show="!state"
        ng-click="selectAirport(airport)">
       {{ airport.name }}
      </div>
    </div>
  </div>
</div>

這是如何傳遞組件以在視圖中使用的方式

  <div class="control">
    <label for="from">From:</label>
    <selector-component id="from"></selector-component>
  </div>
  <div class="control">
    <label for="to">To:</label>
    <selector-component id="to"></selector-component>
  </div>

這是機場選擇器組件,實際上沒有進行任何操作。

import template from './airport-selector.html';

export const AirportSelectorComponent = {
  template
};

由於selector-component是AngularJS組件,因此它能夠接受屬性綁定。

您可以這樣更改組件的注冊:

angular.module( ... )
  .component('selectorComponent', {
    ...
    bindings: {
      value: '<'
    },
    ...
  });

這將自動將變量value綁定到控制器,可以使用$ctrl.value在模板中進行訪問。

同樣,可以像這樣傳遞value

<selector-component value="bind the value here">

有關更多詳細信息,請參考文檔

如果選擇器組件是您的指令,則

app.directive('directiveName', function(){
   return {
      restrict:'E',
      scope: {
         title: '@'
      },
      template:'<div class="title"><h2>{{title}}</h2></div>'
   };
});

根據要綁定的方式/方式,您有不同的選擇:

=是雙向綁定

@只需讀取值(單向綁定)

&用於綁定功能

您應該在這里進行更多研究

暫無
暫無

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

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