在指令中使用 $http 和 $templateCache 不会返回结果

2024-05-08

我正在尝试创建一个加载模板的指令。然后模板将被缓存,因此当您第二次单击该元素时,它不会尝试加载它,而是从 $templateCache 获取最近加载的值。

我注意到,如果缓存命中,我不会从 $http.get() 方法得到任何响应。

<html ng-app="website">
<body ng-controller="MyController">
    <a href='#' ng-click="load()">Click Event</a>
    <a href='#' click-load>Click Directive</a>

</body>
</html>​

angular.module('website', []).directive('clickLoad', function($q, $http, $templateCache) {
    return function(scope, element, attrs) {
        function loadData() {
            $http.get('http://fiddle.jshell.net', {
                cache: $templateCache
            }).then(function(result) {
                alert('loaded ' + result.data.length + " bytes");
            });

        }
        element.bind('click', loadData);
    };
});


function MyController($scope, $http, $templateCache) {
    $scope.load = function() {
        $http.get('http://fiddle.jshell.net', {
            cache: $templateCache
        }).then(function(result) {
            alert('loaded ' + result.data.length + " bytes");
        });
    }
}

我创建了一个模拟我的场景的小提琴:

http://jsfiddle.net/3ea64/ http://jsfiddle.net/3ea64/

请注意,您可以根据需要多次单击“单击事件”链接,但是,如果您先单击“单击指令”链接,则该链接仅有效一次;如果您先单击“单击事件”链接,则该链接根本不起作用。

任何想法都将不胜感激。


我玩了一下并使用了 AngularJS 的缓存(此处描述:http://docs.angularjs.org/api/ng http://docs.angularjs.org/api/ng.$http)

这是一个现场演示:http://jsfiddle.net/4SsgA/ http://jsfiddle.net/4SsgA/

我基本上调整了 $http 语法并使用 ng-click 指令,而不是在指令内注册事件侦听器(只是因为我更喜欢它:))

HTML:

<html ng-app="website">
<body ng-controller="MyController">
    <a href='#' ng-click="load()">Click Event</a>
    <a href='#' click-load ng-click="loadData()">Click Directive</a>
</body>
</html>​

JS:

angular.module('website', []).directive('clickLoad', function($q, $http, $templateCache) {
    return function(scope, element, attrs) {
        scope.loadData = function() {
            $http({method: 'GET', url: 'http://fiddle.jshell.net', cache: true}).then(function(result) {
                alert('loaded ' + result.data.length + " bytes");
            });
        }
    };
});


function MyController($scope, $http, $templateCache) {
    $scope.load = function() {
        $http({method: 'GET', url: 'http://fiddle.jshell.net', cache: true}).then(function(result) {
            alert('loaded ' + result.data.length + " bytes");
        });
    }
}​
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在指令中使用 $http 和 $templateCache 不会返回结果 的相关文章

随机推荐