2014-04-24 63 views
0

我有兩個按鈕,就像收音機組一樣。基本上:如果我點擊一個按鈕,它是活動的,它的值由Angular $ .watch()監視。

我與真正的單選按鈕做到了:

HTML

<form id="switch-view"> 
        <div class="radio-inline"> 
         <label> 
         <input type="radio" ng-model="srcUrl" name="optionsRadios" id="optionsRadios1" value="/me/has" checked="" > 
         Label 1 
         </label> 
        </div> 
        <div class="radio-inline"> 
         <label> 
         <input type="radio" ng-model="srcUrl" name="optionsRadios" id="optionsRadios2" value="/me/wants"> 
         Label 2 
         </label> 
        </div> 
       </form> 

角:

$scope.$watch('srcUrl', function() { 
    console.log($scope.srcUrl); 
    $http({ 
     method: 'GET', 
     url: $scope.srcUrl, 
     headers: { 
     'Accept': 'application/json' 
     } 
    }).then(function(res){ 
     $scope.items = angular.fromJson(res.data) 
      .sort($scope.SortByName) 
      .map(function(e){ 
       e.image = $sce.trustAsHtml(e.image); 
       return e; 
      }); 
     $scope.newItems = $scope.items; 
     if($scope.newItems.length === 0) { 
      $scope.message = ""; 
     } 
     //console.log($scope.items); 
     $scope.checkPagination(); 
    }); 
}); 

上面的代碼按預期工作。現在我希望這與以下HTML一起使用:

<form id="switch-view"> 
        <button class="btn btn-primary active" id="dash-btn-collection" ng-model="srcUrl" value="/me/has">Label 1</button> 
        <button class="btn btn-primary violet" id="dash-btn-wantlist" ng-model="srcUrl" value="/me/wants">Label 2</button> 

       </form> 

任何想法?

回答

2

所以,你想擁有像收音機行爲,也許是這樣的:

<form id="switch-view"> 
    <button class="btn btn-primary active" id="dash-btn-collection" ng-click="srcUrl = URL.HAS" ng-class="{'active': srcUrl == URL.HAS}">Label 1</button> 
    <button class="btn btn-primary violet" id="dash-btn-wantlist" ng-click="srcUrl = URL.WANTS" ng-class="{'active': srcUrl == URL.WANTS}">Label 2</button>  
</form> 

的CSS類「主動」表示當前激活按鈕那裏。

也許你想與ngClick

+0

我想,SO發佈之前,但它不工作,我不知道爲什麼......無論如何,我還需要ng級的東西,所以我選擇你的答案:) – enguerranws

0

刪除守望觸發數據加載只需設置值可能就足夠了:

<form id="switch-view"> 
    <button class="... active" id="dash-btn-collection" ng-click="srcUrl='/me/has' " >Label 1</button> 
    <button class="... violet" id="dash-btn-wantlist" ng-click="srcUrl='/me/wants' " >Label 2</button> 

</form> 
+0

請仔細闡述爲什麼這需要downvoted? – BiAiB

相關問題