javascript - 如何构建指令以自定义带标签的单选按钮

标签 javascript jquery angularjs

这是一个自定义的单选按钮:

enter image description here

Angular HTML 代码:

<div ng-app="app">
   <div ng-controller="ctrl" class="sm-box">
      <p>Please select a mode:
      <sm-radio model="mode" value="MODE1" label="One" ng-click='mode="MODE1"'></sm-radio>
      <sm-radio model="mode" value="MODE2" label="Two"></sm-radio>
      <sm-radio model="mode" value="MODE3" label="Three"></sm-radio></p>
      <p>Selected mode is: {{mode}}</p>
   </div>
</div>

对应的JavaScript:

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

app.controller('ctrl', ['$scope', function( $scope ) {
   $scope.mode = 'MODE1';
}]);

app.directive('smRadio',  ['$compile', function($compile) {
   return {
      restrict: 'E',
      template: function( tElt, tAttrs ) {
         tElt.addClass( 'sm-radio' );
         tElt.append(
            '<input type="radio"' +
            ' name="'     + tAttrs.model + '"' +
            ' ng-model="' + tAttrs.model + '"' +
            ' value="'    + tAttrs.value + '"' +
            ' /><label>'  + tAttrs.label + '</label>'
         );
         if( ! tElt.attr('ng-click')) {
            // This is a first try
            tElt.attr('ng-click', 'mode="' + tAttrs.value + '"' );
            // this is a variant
            tElt.ngClick = 'mode="' + tAttrs.value + '"';
            // None has effect...
            $compile(tElt); // compilation here had twice elements!!!
         }
      }
   };
}]);

问题是“一”是可点击的,并将模型“模式”设置为“模式 1”,但“二”和“三”不是,只有单选按钮可以选择“模式 2”或“模式 3”。

如您在 HTML 源代码中所见,第一个具有“ng-click”属性,而另一个没有。我试图通过代码在我的指令中添加“ng-click”属性,但我没有成功。

如何在指令中添加“ng-click”属性?

编辑:完全不使用 ng-click 的答案指南,因此标题已更新

最佳答案

通过使用隔离范围将值传递给来自“外部世界”的指令被认为是最佳实践。如您所见,它也使它变得更容易:

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

app.controller('ctrl', ['$scope', function( $scope ) {
   $scope.mode = 'MODE1';
}]);

app.directive('smRadio', function($compile) {
   return {
      restrict: 'E',
      scope: {
        model: '=',
        value: '@',
        label: '@'
      },

      template: '' +
        '<input type="radio" name="name" ng-model="model" value="value"' +
        ' ng-checked="model==value" ng-click="model=value">' +
        '<label ng-click="model=value">{{label}}</label>',

      compile: function(tElt) {
         tElt.addClass( 'sm-radio' );
      }
   };
});

这是工作示例:http://jsbin.com/fejori/3/edit?js,output

(如果指令的“template”属性中有这么多代码,我会将其移至外部 html 文件并使用 templateUrl 属性链接它)

关于javascript - 如何构建指令以自定义带标签的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30854224/

相关文章:

jQuery 移动 : Can I "uninitialize" the page?

angularjs - 保持 Angular Controller 薄

angularjs内存消耗问题

javascript - 如何清除主干中点击路由器上的javascript全局变量的值

javascript - 使用 Javascript 和 HTML 表单向 Facebook 提交图像

javascript - 在 http 请求中包含 Web token

javascript - Rails 3 - "link_to_function"方法的状态

jquery - 使用 jquery 创建 div 元素并添加内部 html

javascript - 当我有定时轮询功能时,如何手动调用它?

javascript - 在 AngularJS 中引用 $scope 的更好方法