Angularjs use custom interpolation symbols for scope

孤人 提交于 2019-12-04 05:39:28

Ok, you have a couple issues here, but I found a solution for you.

Demo

http://jsfiddle.net/colllin/zxwf2/

Issue 1

Your < and > characters are being converted to &lt; and &gt;, so when you call element.html(), you won't even find an instance of < or > in that string.

Issue 2

Since the $interpolate service has already been "provided" by the $interpolateProvider, it doesn't look like you can edit the startSymbol and endSymbol. However, you can convert your custom startSymbol and endSymbol to the angular start/end symbols dynamically in your linking function.

Solution

myApp.directive('underscoreTemplate', function ($parse, $compile, $interpolate) {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            var startSym = $interpolate.startSymbol();
            var endSym = $interpolate.endSymbol();
            var rawExp = element.html();
            var transformedExp = rawExp.replace(/&lt;%=/g, startSym).replace(/&lt;%-/g, startSym).replace(/%&gt;/g, endSym);
            var parsedExp = $interpolate(transformedExp);

            scope.$watch(parsedExp, function(newValue) {
                element.html(newValue);
            });
        }
    }
});

Alternatives

I'm not sure how, but I'm sure there's a way to instantiate your own custom $interpolate service using the $interpolateProvider (after configuring it for underscore tags).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!