簡體   English   中英

動態訪問方法中的控制器變量

[英]Access controller variables in methods dynamically

我有一個角度控制器,卡片中有一個巨大的形狀。 因此,每次用戶選擇標題時,該部分的卡片都會顯示(例如姓名部分,地址部分,聯系人數據,大學數據,工作數據等)。

僅使用兩個部分執行此操作的相關代碼如下:

angular.module('controllers', [])
.controller('EditUserController', function($scope, $state) {

  $scope.mustShowName = false;
  $scope.mustShowContact = false;

  $scope.toogleShowContact = function() {
    if ($scope.mustShowContact) {
      $scope.mustShowContact = false;
    } else {
      $scope.mustShowContact = true;
    }
  };
  $scope.toogleShowName = function() {
    if ($scope.mustShowName) {
      $scope.mustShowName = false;
    } else {
      $scope.mustShowName = true;
    }
  };
});

但是有各種卡片。 有一種方法可以像這樣重構一下嗎?:

$scope.toogleSection = function(section) {
  if (section) {
    section = false;
  } else {
    section = true;
  }
};

...

$scope.toogleSection($scope.mustShowName);

如果我嘗試它,它不起作用並且不會拋出錯誤,所以我認為它只是復制變量而不是引用原始變量。

您可以重構它,以便您可以將屬性的名稱作為參數發送到函數,如下所示:

$scope.toggleSelection = function(sectionName) {
  $scope[sectionName] = !$scope[sectionName];
};

當你要求$scope.mustShowName你只需要獲取值而不是屬性的引用 - 即true或false。 而是將節名稱作為字符串傳遞,並使用名稱引用范圍中的屬性。

順便說一句 - 更好的想法是創建一個封裝行為的指令,並幫助你保持DRY

$scope.toogleSection = function(sectionName) {
  if ($scope[sectionName]) {
    $scope[sectionName] = false;
  } else {
    $scope[sectionName] = true;
  }
};

$scope.toogleSection('toogleShowName');

你可以使用ng-if =“show”來獲得卡片的詳細部分。 然后執行ng-click =“show =!show”。 BAM! 你有一個觸摸切換,將顯示和隱藏你放置的ng-if。 這是我制作的應用程序的示例。

<div class="item" ng-show="directions">
    <!--directions go here-->
</div>
    <div style="text-align: center; background-color:#284f9a;" class="item" ng-click="directions = !directions">
        <p style="color: white;" ng-if="directions == false">See Directions:</p>
        <p style="color: white;" ng-if="directions == true">Close Directions:</p>
</div>

有了這個,我可以顯示和隱藏方向,並改變顯示/隱藏按鈕所說的內容。 這對於ng-repeat也很有效,只能切換你點擊的項目。

暫無
暫無

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

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