使用AngularJS在bootstrap-switch元素上设置事件处理程序时遇到问题

时间:2015-07-22 21:56:17

标签: javascript angularjs twitter-bootstrap javascript-events bootstrap-select

所以上下文是我的角度应用程序中有一个单选按钮,触发一个下拉菜单。我试图附加一个事件监听器,它将向服务器发出一个AJAX请求并用响应填充下拉列表。我正在使用angular-bootstrap-select / bootstrap-select作为交换机。

我最初的方法是简单地将ng-click指令添加到按钮周围的div,该指令有效,但只有当用户点击按钮的白色部分时才会发送请求:

按钮图片:http://imgur.com/YBOT6x1

但是,如果用户点击其中所示的灰色部分"全部",则点击不会注册。我也尝试将div包装在一个锚中并将ng-click附加到那个但是也没用。

我也尝试过使用文档中的方法: bootstrap-switch-event

我的代码:

    $('input[id="mySwitch"]').on('switchChange.bootstrapSwitch', function(event, state) {
    console.log('event triggered');
    if ( !itemsCalled ) {
        myService.items.get().$promise.then(function(response) {
            $scope.itemList = response.items;
        });
        itemsCalled = true;
    }
});

模板:

<input bs-switch id="mySwitch" ng-model="item" type="radio" switch-on-text="All" switch-off-text="Custom" switch-on-color="grey" switch-off-color="blue" switch-animate="true" switch-size="small" ng-value="'All'" ng-true-value="'All'" ng-false-value="'Custom'">

这一系列的变化没有成功。我对角度很陌生,所以我不确定我是否会以错误的方式解决这个问题。提前感谢任何建议!

1 个答案:

答案 0 :(得分:0)

如果您想在交换机从"Custom"更改为"All"时进行Ajax调用:

function Controller($scope) {
    $scope.$watch('item', function(newValue, oldValue){
        if(newValue === "All") {
           // Ajax call
          alert("ajax");
        }
    })
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="Controller">

<input ng-model="item" type="radio" ng-value="'All'" ng-true-value="'All'" ng-false-value="'Custom'">
  
<button ng-click="item = 'Custom'">Reset</button>
  
</div>