AngularJS directive Example

by Kai_Draord

HTML

<div ng-controller='myctrl'>
  <hello-world name="name"></hello-world>
  <div>

CSS

.ng-scope {
  border: 1px red solid;
}

JavaScript

angular.module('components', []).directive('helloWorld', function($compile) {
  return {
    restrict: 'E',
    scope: {
      name: '='
    },
    template: '<span>Hello {{name}}</span>',
    link: (scope, element, attrs) => {
      var aTag1 = document.createElement('a');
      aTag1.innerHTML = 'testing'
      aTag1.setAttribute('ng-click', "setID(" + "'test'" + ")");
      var test = $compile(aTag1)(scope);
      element.append(test);
      scope.setID = function(value) {
        console.log(value);
      }
    }
  }
})

angular.module('myApp', ['components']).controller('myctrl', ['$scope', function($scope) {
  $scope.name = 'test';
}]);