Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save phplaw/bd35025db17c7b840770dbe3dbe4e48c to your computer and use it in GitHub Desktop.
Save phplaw/bd35025db17c7b840770dbe3dbe4e48c to your computer and use it in GitHub Desktop.
use $compile outside a directive in Angularjs
$(function() {
// myApp for test directive to work, ng for $compile
var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
$('body').prepend($compile('<div ng-attr-tooltip="test">Cancel</div>')($rootScope));
});
});
/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myDefaultAppName";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
var ctrName = $(htmlToCompile).attr('ng-controller');
_log(ctrName);
var _scope = AngularHelper.getScope(ctrName);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = _scope || $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
//$rootScope.$digest();
if ($scope) {
$scope.$digest();
$scope.$apply();
}
}]);
};
AngularHelper.getScope = function(ctrlName) {
let sel = 'div[ng-controller="' + ctrlName + '"]';
return angular.element(sel).scope();
};
return AngularHelper;
})();
$.ajax("myTemplate.html"), {
success : function(view){
//Append the template
$("body").append("<div id='my-template-scope'>");
var $targetDom = $("#my-template-scope");
//Compile it to bind it with angular
AngularHelper.Compile($targetDom, view)
}
});
@phplaw
Copy link
Author

phplaw commented Jul 10, 2018

(function() {
  angular
    .module('jgefrohModule')
    .factory('PopupOnErrorInterceptor', [$q', '$injector', Interceptor])
    .config(['$httpProvider', Configuration]);
  function Interceptor($rootScope, $q, $injector) {
    var UNPROCESSABLE = 422;
    var SERVER_ERROR = 500;
    return {
      responseError: function(response) {
        var popup = $injector.get('popup'); //[JG]: Use injector to get services you typically don't have access to due to circular references!
        if (response.status === UNPROCESSABLE) {
          popup.error('Please fix the issues and try again!', 'There\'s issues with the form.');
        }
        else if (response.status === SERVER_ERROR) {
          popup.error('Sorry, something went wrong with the server. Please contact [email protected] if it continues.');
        }
        return $q.reject(response);
      }
    };
  }
  function Configuration($httpProvider) {
    $httpProvider.interceptors.push('PopupOnErrorInterceptor');
  }
})();

@phplaw
Copy link
Author

phplaw commented Jul 10, 2018

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Code reuse with Script-Block - ng-include</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
</head>
<body ng-app>

  <script type="text/ng-template" id="my_template.tmpl">
    <p>
      I am Nr. {{ i }}!
    </p>
  </script>

  <div ng-repeat="i in [1, 2, 3]">
    <div ng-include="'my_template.tmpl'"></div>
  </div>

</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment