角度js中单选按钮的自定义指令

时间:2015-04-13 05:51:15

标签: angularjs angularjs-directive

为角度js

创建单选按钮的自定义指令

我到目前为止尝试了

HTML:

  <my-raido></my-raido>
  <my-raido></my-raido>
  <my-raido></my-raido>

Angular js:

var App = angular.module('myRaido',[]);

App.directive('myRaido',function() {

    return {
        restrict : 'E',
        template:  '<div class="myClass"><input type="radio"></div>',
        replace:true,
        link:function (scope, element, attrs) {

            element.click(function () {
                console.log("clicked....");
                // body...
            });

            console.log("link should be work as per our expections...", + attrs.valve);
        }
    }
});

提前谢谢

2 个答案:

答案 0 :(得分:1)

var App = angular.module('myRaido',[]);

App.directive('myRaido',function() {

return {
    restrict : 'E',
    template:  '<div class="myClass"><input type="radio" name='fooRadios'></div>',
    replace:true,
    link:function (scope, element, attrs) {

        element.click(function () {
            console.log("clicked....");
            // body...
        });

        console.log("link should be work as per our expections...", + attrs.valve);
    }
  }
});

答案 1 :(得分:1)

您应该在广播元素上设置name属性,使其成为群组的一部分。

angular.module('app', [])
.directive('myRadio', function() {
    return {
        restrict : 'E',
        template:  '<div class="myClass">\
                      <label>\
                        <input type="radio">\
                        <span></span>\
                      </label>\
                    </div>',
        replace: true,
        link: function (scope, element, attrs) {
            var $radio = element.find('input');
            var $span = element.find('span');

            $radio.attr('name', attrs.group);
            $span.html(attrs.label);
        }
    }
});

如果多个输入[radio]控件具有相同的名称,它们将表现为一个组。

您可以像这样使用此指令:

<my-radio group="group1" label="Option1"></my-radio>
<my-radio group="group1" label="Option2"></my-radio>
<my-radio group="group1" label="Option2"></my-radio>