角度方面的Checkbox指令

时间:2016-05-03 05:19:57

标签: javascript jquery angularjs checkbox

我希望使用此结构的复选框输入创建指令:

<label for="sameID" class="style">
  <input type="checkbox" id="sameID" name="name" />
  <span>some text here</span>
</label>

并在我的html中添加了像<checkbox></checkbox>这样的简单标记。 这个指令应该为我处理检查事件。我可以检查代码中是否选中了此复选框。

尝试创建此指令时,这是我的js代码:

app.directive("checkbox", function($compile){

  var check = "{{check}}";
  if (check == true) {
    var inputCheck = '<input class="checkbox" checked type="checkbox" ng-change="isChecked()" name="{{for}}" id="{{for}}" />';
  } else {
    var inputCheck = '<input class="checkbox" ng-change="isChecked()" type="checkbox" name="{{for}}" id="{{for}}" />';
  }
  var temp = '<label for="{{for}}" class="hello">'+inputCheck+' <svg width="100%" v-pressable id="checkboxsvg" height="100%" viewBox="0 0 23 23" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve">'+'<g transform="matrix(1,0,0,1,-262.373,-219.494)">'+'<g id="checkbox-background" transform="matrix(1,0,0,1,73.0395,6.16767)"><path d="M211.114,216.192C211.114,215.089 210.218,214.192 209.114,214.192L192.199,214.192C191.095,214.192 190.199,215.089 190.199,216.192L190.199,233.107C190.199,234.211 191.095,235.107 192.199,235.107L209.114,235.107C210.218,235.107 211.114,234.211 211.114,233.107L211.114,216.192Z"/></g><g id="checkbox-check" transform="matrix(1,0,0,1,35.2522,0.0159298)"><path  d="M234.362,231.155L237.395,234.188L243.299,228.283"/></g></g></svg><span>{{p}}</span></label>';

  return {
    restrict: "E",
    template : temp,
    scope : {},
    link : function(scope, element, attrs, ctrl){

      scope.type = attrs.type;
      scope.p = attrs.p;
      scope.for = attrs.for;
      scope.check = attrs.check;

      scope.isChecked = function() {
        console.log("checked");
      }
    }
  };
});

我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

请检查一下

var jimApp = angular.module("mainApp",  []);

jimApp.controller('mainCtrl', function($scope){
})
.directive("checkbox", function() {
    return {
        restrict : "E",
        require: 'ngModel',
        scope:{ name:"@" , ngModel:"=" },
        template : "<label class='style'><input type='checkbox' name='name' ng-model='ngModel' /><span>{{name}}</span></label>"
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
  <checkbox name="some text here" ng-model="value" ></checkbox>
  {{value}}
</div>