AngularJS: select a radio button by clicking on an external element

I have the following code inside an angularjs application:

    <div class="radio input-group-addon">
      <label>
        <input type="radio" name="radio1" value="foobar" ng-model="myModel" />
        my label
      </span>
    </div>

The outer div has 100% background color. Now I want to make the entire area (the entire container of the container) available. I tried it with a handler ng-clickon a div like this:

    <div class="radio input-group-addon" ng-click="selectRadio($event)">
      <label>
        <input type="radio" name="radio1" value="foobar" ng-model="myModel" />
        my label
      </span>
    </div>

The method is selectRadio($event)as follows:

$scope.selectRadio = function($event) {
  var radio = $(event.currentTarget).find("input[type='radio']");
  radio.prop("checked", true);
  radio.trigger("change");
}

Unfortunately, this does not cause a change on myModel. Is there a way to trigger the "change-bind-change" event (I don’t know how to designate this correctly) to update my switch model?

And besides, I was wondering if there is a more angular -way for this?

+4
source share
4 answers

- :

<div class="radio input-group-addon" ng-click="myModel = 'foobar'">
  <label>
    <input type="radio" name="radio1" value="foobar" ng-model="myModel" />
    my label
  </label>
</div>
+5

input , :

$scope.selectRadio = function($event) {
    scope.myModel = 'foobar';
}
+3

I created a small directive for him, this may not be the best answer, but it solves the problem

Common.directive('radiobtn',function(){
    return {
        link:function(scope,elem,attr){
            var value=attr['radiobtn'];
            var radio=elem.find('input[type=radio]').first()
            if(radio.val()==value){
                elem.addClass('active');
            }
            radio.click(function(e) {
               //do something
               e.stopPropagation();
            })
            elem.on('click',function(event){
                //elem.addClass('active');
                radio.prop("checked", true);
                radio.trigger('click');



            });
        }
    }
});

You can use this directive in the tag tag.

+1
source

HTML

<div ng-repeat="item in $scope.items track by $index" ng-click="$scope.SelectRadio($index)">
    <input type="radio" name="radio1" ng-checked="$scope.clicked == $index" />
</div>

controller

$scope.SelectRadio = function (rowIndex) {
    $scope.clicked = rowIndex;
}
0
source

Source: https://habr.com/ru/post/1532301/


All Articles