2017-04-12 51 views
0

迭代有三個複選框: -我怎樣通過複選框對象

<label>Type:</label> 
<label>one</label> 
    <input type="checkbox" name="type" ng-model="a.Type[0]"/> 

    <label>two</label> 
    <input type="checkbox" name="type" ng-model="a.Type[1]"/> 

    <label>three</label> 
    <input type="checkbox" name="type" ng-model="a.Type[2]"/> 

這些複選框被存儲在後端作爲字符串的數組。

我值顯示在: -

<li class="list-group-item"><strong>Type</strong>: <span ng-repeat="values in myArray">{{values}}</span></li> 

我的指令代碼是: -

(function() { 
    'use strict'; 
    angular.module('myApp.components') 
     .directive('abc', abc); 

    abc.$inject = ['$http', '$timeout', 'ApiServices']; 

    function abc($http, $timeout, ApiServices) { 
     return { 
      restrict: 'EA', 
      scope: { 

      }, 

      link: function (scope, el, attrs) { 
       scope.a = {}; 

       $('#abc').on('hide.bs.modal', function() { 
        scope.active = false; 
       }); 
       $('#abc').on('shown.bs.modal', function() { 
        scope.active = true; 

        scope.myArray = []; 

        scope.iterate = function() { 
        for (var key in scope.a.Type) { 
         if (scope.a.Type.hasOwnProperty(key)) { 
         scope.myArray.push(scope.a.Type[key]); 
         } 
        } 
        }; 

        scope.iterate(); 
      }, 
      templateUrl: '' 
     }; 
    } 

})(); 

這裏我所試圖做的是 - 我想通過「類型」複選框和迭代將'myArray'中的值推入,然後僅顯示值。

+0

這是不是很清楚你在這裏試圖做什麼。你正在顯示一個未知指令的'link'函數,並且鏈接函數似乎試圖通過一個空對象立即迭代*。你爲什麼試圖遍歷數組呢? '$ scope.a.Type'不會是你正在尋找的數組嗎?例如你能不能在$ scope.a.Type中使用'ng-repeat =「值? – Claies

+0

scope.a.Type在後端字符串數組中的類型,但是當我保存這些值時,它們將存儲爲對象,其中鍵是索引號,值是名稱; - 一,二,三。所以,我正在做的是遍歷該對象並獲取值,然後將它們推入'myArray',然後顯示數組的值。 –

+0

但你不是(至少不在此代碼中)。我不知道你的指令在做什麼,但是這個鏈接函數設置了'scope.a = {};',然後立即嘗試遍歷它。 – Claies

回答

0

也許,下面我舉的例子有點類似於你在找什麼:

HTML:

<span>Select Type:</span> 
    <div ng-repeat="type in myArray"> 
    <input type="checkbox" ng-model="type.value" /> {{type.type}} 
    </div> 

    <span>Selected Types:</span> 
    <div ng-repeat="type in myArray"> 
    <span ng-show="type.value"> {{type.type}}</span> 
    </div> 

JS:

$scope.a = {}; 
    $scope.a.Type = ["One","Two","Three"]; // your string array 

    $scope.myArray = []; 
    $scope.a.Type.forEach(function(item){ 
    $scope.myArray.push({type: item, value: false }); // create new array to make it selectable via checkbox 
    }); 

我猜,你沒有更多需要你的指導現在。迭代和過濾在HTML本身中完成。

我希望這會有所幫助。