iCode
iCode

Reputation: 9202

Bind custom methods and class mentioned in HTML to Directive template

Hi I have created a directive for toggle button.

DIRECTIVE

app.directive('toggleBtn',[function () {
    return {
      restrict: 'EA',
      replace: true,
      require: ['name', '^ngModel'],
      scope: {
        isDisabled: '=',
        name: '@',
        ngModel: '='
      },
      template:
          ' <div class="toggle-switch on off"> ' +
          '     <input ng-model="ngModel" id="{{name}}" type="checkbox" ng-disabled="{{isDisabled}}" ' +
          '         hidden=""><label for="{{name}}" ' +
          '         class="ts-helper"></label> ' +
          ' </div> '
    };
  }]);

HTML

 <input ng-model="sample1" name="sample1"
                            type="checkbox" class="someclass" ng-change="doSomething()" toggle-btn>

Directive is working fine, except ng-change. ng-change attribute is added to div, not to input-checkbox.

How to add those attributes to input-checkbox?

Not just ng-change, there can be other attributes also. Like ng-focus, title, ng-click, etc... (ng-click and title will work as it will append to main div, I'm just giving an example here).

Plunkr Demo here

Upvotes: 0

Views: 287

Answers (1)

Shamal Perera
Shamal Perera

Reputation: 1671

Change your code to this

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.doSomething = function() {
    console.log("Do something");

  }
});

app.directive('toggleBtn', [function() {
  return {
    restrict: 'EA',
    replace: true,
    require: ['name', '^ngModel'],
    scope: {
      isDisabled: '=',
      name: '@',
      ngModel: '=',
      ngChange: '&'
    },
    template: ' <div class="toggle-switch on off"> ' +
      '     <input ng-model="ngModel" id="{{name}}" type="checkbox" ng-change="ngChange()" ng-disabled="{{isDisabled}}" ' +
      '         hidden=""><label for="{{name}}" ' +
      '         class="ts-helper"></label> ' +
      ' </div> '
  };
}]);

Demo

Upvotes: 1

Related Questions