Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
缓存AngularJS指令的编译模板_Angularjs_Angularjs Ng Repeat_Angular Directive_Angular Cache - Fatal编程技术网

缓存AngularJS指令的编译模板

缓存AngularJS指令的编译模板,angularjs,angularjs-ng-repeat,angular-directive,angular-cache,Angularjs,Angularjs Ng Repeat,Angular Directive,Angular Cache,我有一个模板的指令,它有很多重复,需要一些时间来渲染,我同意。但问题是,我在同一个视图中多次调用此指令。因此,它导致了大量的冻结和性能问题,因为指令的每个实例都会发生ngRepeat 该指令的每个实例的模板都是相同的,因此如果我只能在第一次编译它,缓存编译的html并将其用于另一个指令实例,那就太好了。这是我的解决方案,虽然脏,但工作正常 我所做的是在指令函数中与XMLHttpRequest同步加载模板,然后在指令的控制器中只编译一次 .directive('myDirective', func

我有一个模板的指令,它有很多重复,需要一些时间来渲染,我同意。但问题是,我在同一个视图中多次调用此指令。因此,它导致了大量的冻结和性能问题,因为指令的每个实例都会发生ngRepeat


该指令的每个实例的模板都是相同的,因此如果我只能在第一次编译它,缓存编译的html并将其用于另一个指令实例,那就太好了。

这是我的解决方案,虽然脏,但工作正常

我所做的是在指令函数中与XMLHttpRequest同步加载模板,然后在指令的控制器中只编译一次

.directive('myDirective', function($compile) {
     var cachedTemplate = null,
         templateCompiled = false;

    var xhr = new XMLHttpRequest();

    // do an asynchronous request to wait until we load the template
    xhr.open('GET', 'directives/template.html', false);
    xhr.send(null);

    if (xhr.status == 200) {
        cachedTemplate = xhr.responseText;
    }

    return {
        restrict: 'E'
        scope: {
        date: 'someData'
    }

    controller: function($scope, $element, $attrs) {
        if (!templateCompiled) {
          // compile the template only one time.
            cachedTemplate = $compile(cachedTemplate)($scope);
            templateCompiled = true
        }

        // replace/include the compiled template in our $element
        $element.replaceWith(cachedTemplate);
        // ... do the job....
    }
}

这里有一个竞争条件,Ajax调用可能无法在调用控制器函数之前及时返回。编辑:没关系,我注意到您进行了一个同步调用-这解决了竞争条件,但会导致您的浏览器冻结。