简体   繁体   中英

$http.get breaks AngularJS variables from response data

I'm trying to cache a html file containing some angular variables, but when I append the file contents to dom, all the variables are just plain text like {{ variable.name.here }}

I'm retrieving the html file with $http.get like this:

$http.get('app/shared/partials/raise-error.html').then(function(res){
    $templateCache.put('raiseErrorBlock', res.data);
});

...and this is the raise-error.html (part of it):

<div id="raiseError" ng-show="errorParams.raise" class="slide-down">
    <div class="raiseErrorWrapper">
        <div class="rew-header">
            <i class="fa fa-bug"></i>
            <span class="rewh-title">{{ errorParams.title }}</span>
        </div>
    </div>
</div>

I'm running the $http.get inside run() block for any matter.

EDIT: from what i can see it's a templateCache issue. Does templateCache have support for variables or it can only cache static data?

You have to use $compile service to make angular expressions work properly.

var $el = $compile('<div>{{myData}}</div>')(scope);
$body.append($el); // wrapped $body with jqLite

As ngdoc says:

$compile - Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

You can also use shorter method of storing something in $templateCache eg.

$http.get('http://myserver.com/file.html', {
    cache: $templateCache
}).then(function(response) {
  // do sth
});

I also created plnkr for you. Hope it will help you. http://plnkr.co/edit/ls4kllAvdVb3qMvm3mBA?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM