0

我會盡量簡化問題。比較兩個示波器提供的值

比方說,我有2米範圍

$scope.section1 = [ 
    {label: 'label1'}, 
    {label: 'label2'} 
]; 

$scope.section2 = [ 
    {value: 'one'}, 
    {value: 'two} 
]; 

這些範圍被用來生成NG-重複按鈕

<button ng-repeat="item in section1 type="button">{{item.label}}</button> 

<button ng-repeat="item in section2 type="button">{{item.value}}</button> 

現在我想做些什麼它創建第三個作用域,將值附加到前兩個對象的組合中,例如:

$scope.combo = [ 
    { section1.label:label1 + section2.value: one = 'result1' }, 
    { section1.label:label2 + section2.value: one = 'result2' }, 
    { section1.label:label1 + section2.value: two = 'result3' }, 
    { section1.label:label2 + section2.value: two = 'result4' } 
]; 

現在來了棘手的部分。我需要做的是添加一個函數,該函數將採用每個部分中單擊的ng-repeat按鈕的值,然後根據輸入字段中的第三個範圍顯示結果。

因此,如果您單擊標籤爲label1的按鈕和值爲two的輸入字段將顯示result3。

對於Angular,我非常青睞,我不知道如何接近它,尤其是所有值都是字符串。

+0

BTW小心你的術語。你只有一個作用域,section1,section2和combo只是在這個單一作用域上創建的數組/對象。 – haggisandchips

回答

1

如果我理解正確,你可以設置您的組合像...

$scope.combo = { 
    "label1": { 
     "one": "result1", 
     "two": "result2" 
    }, 
    "label2": { 
     "one": "result3", 
     "two": "result4" 
    } 
} 

然後,您可以在模型引用正確的值作爲組合[valueFromButton1] [valueFromButton2]其中valueFromButton1和valueFromButton2點包含點擊按鈕的結果。您的控制器功能只需要通過點擊按鈕時更新模型將所有內容綁定在一起。

看到這個plunkr ... https://embed.plnkr.co/GgorcM/

+0

工程就像一個魅力。而且非常簡單:)輝煌,謝謝。 –

+0

出於好奇。是否有可能從3個或更多的obects形成結果? –

+0

是的,你只需要通過將嵌套在組合中的'one'和'two'值轉換爲代表第三組值的對象來嵌套結果。這種方法不會很容易擴展,您可能會發現Angular_10的方法由於其更線性的方法而更容易維護。如果你堅持我的方法,那麼你只需要附加一個額外的[]訪問器來挑選出第三級的結果。 HTH – haggisandchips

1

沒有太大變化,你也可以嘗試像下面提供的代碼snippet.Run它來檢查演示。

var app = angular.module('app', []); 
 
app.controller('Ctrl',['$scope' ,function($scope) { 
 
    var key1, key2; 
 
    $scope.click = function(type, item) { 
 

 
     if (type == 'label') { 
 
      key1 = item; 
 
     } else if (type == 'val') { 
 
      key2 = item; 
 
     } 
 

 
     $scope.key = key1 + '+' + key2; 
 
     angular.forEach($scope.combo, function(val, key) { 
 
      if(val[$scope.key]){ 
 
       $scope.finalVal = val[$scope.key]; 
 
      } 
 
     }); 
 
    }; 
 

 
    $scope.section1 = [{ 
 
     label: 'label1' 
 
    }, { 
 
     label: 'label2' 
 
    }]; 
 

 
    $scope.section2 = [{ 
 
     value: 'one' 
 
    }, { 
 
     value: 'two' 
 
    }]; 
 

 
    $scope.combo = [{ 
 
     'label1+one': 'result1' 
 
    }, { 
 
     'label2+one': 'result2' 
 
    }, { 
 
     'label1+two': 'result3' 
 
    }, { 
 
     'label2+two': 'result4' 
 
    }]; 
 

 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app='app' ng-controller='Ctrl'> 
 

 
<button ng-repeat="item in section1" ng-click="click('label',item.label)" type="button">{{item.label}}</button> 
 

 

 
<button ng-repeat="item in section2" ng-click="click('val',item.value)"type="button">{{item.value}}</button> 
 
    
 
    <input type="text" ng-model="finalVal"/>{{key}} {{finalVal}} 
 
    </div>