Angular$watch<按钮>价值

Angular $watch <button> value

本文关键字:按钮 gt 价值 lt watch Angular      更新时间:2023-09-26

我有两个按钮,就像无线电组一样。基本上:如果我点击一个按钮,它是活动的,它的值由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>

有什么想法吗?

所以你想有一个像无线电一样的行为,也许是这样的:

<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类"active"表示当前的活动按钮。

也许您想删除观察程序并使用ngClick 触发数据加载

只需设置值就足够了:

<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>