2016-08-08 32 views
1

我是網絡開發的新手,我遇到了AngularJS中的數組問題。AngularJS從數組中計算兩個動態值

我有一個ng-repeat序列。在這個序列中有兩個滑塊,由於ng-repeat而反覆重複。

相應的HTML摘錄如下:

<h1>INDEX = {{index}}</h1> 
    <div ng-repeat="alert in alerts"> 
     <rzslider rz-slider-model="alert.value" 
       rz-slider-options="alert.options"></rzslider> 
    <br> 
    <br> 
    <div> 
     <h4>{{alert.weighttitle}}</h4> 
     <div> 
     <md-slider flex md-discrete ng-model="alert.weight" step="1" min="1" max="100" aria-label="rating"></md-slider> 
     </div> 
    </div> 
    </div> 

考慮到所有的所有的鏈接和腳本包括與控制器的設置是否正確。

上面的代碼執行以下操作:

  • 它顯示從angularJS控制器$ scope.index。
  • 出現兩個不同的滑塊,它們遍歷一個名爲alerts的數組。從那裏它需要一些價值。

控制器的有趣片段看起來像這樣:

$scope.alerts = [ 
    { id: 1, 
    title: 'title1', 
    weighttitle: 'weighttitle1', 
    value: 1, 
    weight: 10, 
    options: { 
     showTicks: true, 
     hidePointerLabels: true, 
     hideLimitLabels: true, 
     stepsArray: [ 
     { value: 1, legend: '<10' }, 
     { value: 2, legend: '<50' }, 
     { value: 3, legend: '<250' }, 
     { value: 4, legend: '<500' }, 
     { value: 5, legend: '>500' } 

     ] 
    } 
    }, 
    { id: 2, 
    title: 'title2', 
    weighttitle: 'weighttitle2', 
    value: 5, 
    weight: 1, 
    options: { 
     showTicks: true, 
     hidePointerLabels: true, 
     hideLimitLabels: true, 
     stepsArray: [ 
     { value: 1, legend: '<2Mio' }, 
     { value: 2, legend: '<10Mio' }, 
     { value: 3, legend: '<50Mio' }, 
     { value: 4, legend: '<100Mio' }, 
     { value: 5, legend: '>100Mio' } 

     ] 
    } 
    }, 
    { id: 3, 
    title: 'title3', 
    weighttitle: 'weighttitle3', 
    value: 1, 
    weight: 1, 
    options: { 
     showTicks: true, 
     hidePointerLabels: true, 
     hideLimitLabels: true, 
     stepsArray: [ 
     { value: 1, legend: '<5%' }, 
     { value: 2, legend: '<10%' }, 
     { value: 3, legend: '<15%' }, 
     { value: 4, legend: '<20%' }, 
     { value: 5, legend: '>20%' } 

     ] 
    } 
    }, 
    { id: 4, 
    title: 'title4', 
    weighttitle: 'weighttitle4', 
    value: 3, 
    weight: 69, 
    options: { 
     showTicks: true, 
     hidePointerLabels: true, 
     hideLimitLabels: true, 
     stepsArray: [ 
     { value: 1, legend: '<5' }, 
     { value: 2, legend: '<10' }, 
     { value: 3, legend: '<15' }, 
     { value: 4, legend: '<20' }, 
     { value: 5, legend: '>20' } 

     ] 
    } 
    }, 
]; 

上述片段是被正確地包含在HTML,因此工作的控制器的一部分。

我的問題是,現在我怎麼能成立一個$scope.index使得它使每個value每個weight從陣列和的值相乘,因而相應的value * weight它必須注意的是,用戶可以更改通過改變操縱滑塊,其對應於上述特定的可變陣列

在這個值我嘗試了$監視命令是這樣的:

$scope.$watch('alerts', function(newValue, oldValue){ 
    $scope.index = oldValue + (newValue.weight * newValue.value); 
}, true); 

但它不起作用。

回答

0

您可以使用$scope.$watch並監聽更改,當發生更改時您可以更新視圖。您也可以嘗試使用ng-change="update(alert)"函數並將該值傳遞給函數。

+0

我試過手錶命令,但它不起作用 – danielkr