Directive Auto Wrap In Compile

An example for how to auto wrap a directive with external html structure in the compile function.

by Orri Scott

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='application'>
  <div ng-controller='mainCtrl as ctrl'>
  
    <input wrapped-with-div ng-model='ctrl.inputVal' ng-required="true">
    {{ctrl.inputVal}}
  </div>
</div>

JavaScript

angular.module('directives', []);

angular.module('directives').directive('wrappedWithDiv', [
  function() {
    var definition = {
      restrict: 'A',
      compile: function(element, attrs) {
        element.removeAttr("wrapped-with-div");
        element.replaceWith("<div style='border:2px solid blue'>" +
          element[0].outerHTML + "</div>")
      }

    }
    return definition;
  }
]);


var app = angular.module('application', ['directives']);
app.controller('mainCtrl',
  function($scope) {
    $scope.model = createDemoModel();
    $scope.data = {};
    $scope.onclick = function() {
      alert($scope.f);
    }

    function createDemoModel() {
      $scope.arr = [1, 2, 3];
    }
  });