Dark star
Dark star

Reputation: 5822

Checkbox Directive in angular

I want create directive for checkbox input with this structure:

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

And the put the simple tag like <checkbox></checkbox> in my html. and this directive should handle checked event for me. And i can check if this checkbox checked or not in code.

Here is my js code when try create this directive:

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");
      }
    }
  };
});

How i can do that?

Upvotes: 1

Views: 1622

Answers (1)

byteC0de
byteC0de

Reputation: 5273

Pls check this out

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>

Upvotes: 2

Related Questions