我有一个安格拉斯水疗中心。在应用程序初始化期间,我从服务器获取一个主题,其中包括几个CSS url。
我想使用它们,如果它们404,则返回默认值。
我想我可以设置一个简单的指令来完成这项工作,但我不能让它正常工作。

.directive('errorHref', function() {
    return {
        link: function(scope, element, attrs) {
            element.bind('error', function() {
                attrs.$set('ng-href', attrs.errorHref);
            });
        }
    }
});

HTML:注意,控制器正在工作;但是,headController中的初始化事件比其他事件先触发。
<html ng-app="timeclock">
    <head ng-controller="headController">
        <link ng-href="{{urlToAppCSS}}" error-href="content/css/app.css" rel="stylesheet">

这是正确的方法还是有更好的方法?一切看起来都应该正常工作(在我的应用程序的其他部分中几乎可以在相同的情况下工作),但是element.bind('error'...函数从来没有真正启动过。

最佳答案

我不确定<link>元素是否触发错误事件。所以我建议使用一个指令和<style>元素。请注意,有很多方法可以潜在地执行这样的操作,这只是一个过于简化的示例:

.directive('customStyle', function($http) {
    return {
        restrict: 'E',
        scope: {
            href: '@',
            fallback: '@'
        },
        link: function(scope) {
            $http.get(scope.href)
                    .then(function(response) {
                        // Take the contents of the response and place into
                        // a scope variable for use in the template
                        scope.css = response.data;
                    })
                    .catch(function(response) {
                        // The request failed, so instead try loading from scope.fallback url.
                    });
        },
        template: '<style>{{ scope.css }}</style>'
    }
});

HTML格式:
<custom-style href="{{ urlToAppCSS }}" fallback="content/css/app.css"></custom-style>

您可能希望同时加载回退CSS,以便在无法加载所请求的CSS文件的情况下不会有很长的延迟,但这可能是一个很好的起点。

10-05 21:02
查看更多