Don't work $compile in Jasmine Karma Angular

2019-08-30 10:23发布

问题:

    (function () {
    'use strict';

    angular
        .module('app.widgets')
        .directive('analiticsHere', analitics);

    function analitics() {
        var directive = {
            template: '<div>hello world</div>'
        };
        return directive;
    }
})();

Create simple directive. Ant try to test it.

inject(function($compile, $rootScope, $templateCache){
            compile = $compile;
            scope = $rootScope.$new();
            template = $templateCache.get('scripts/widgets/templates/Analytics.html');
            console.log(template);//return nothing
            var element = angular.element('<div analitics-here></div>');
            var compiledElement = compile(element)(scope);
            console.log('compiledElement'); //return <div analitics-here="" class="ng-scope"></div>
        });

Don't added template code if i use template in directive. But ngHtml2JsPreprocessor create html.js from any my html files.

How make it work? Any ideas?

回答1:

Try following code

inject(function($injector){
        compile = $injector.get("$compile");
        scope = $injector.get("$rootScope").$new();
        template =$injector.get("$templateCache").get('scripts/widgets/templates/Analytics.html');
        console.log(template);
        var element = angular.element('<div analitics-here></div>');
        var compiledElement = compile(element)(scope);
        console.log('compiledElement'); class="ng-scope"></div>
    });