我有一个 Angularjs 指令“ExampleDirective”,它具有控制器“ExampleController”。控制器定义了两个 Promise 对象,其中每个 Promise 对象发出 Http GET 请求并返回响应。
在指令中,我们从 Promise 对象获取响应数据并处理它们以呈现指令。
ExampleDirective 在同一视图中实例化两次,每个实例都会发出自己的 Http GET 请求。由于同时发送两个请求来进行昂贵的数据库调用并从同一个表中读取,这会导致前端出现性能问题。
控制器:
angular.module('exampleModule')
.constant("EXAMPLE_URL", "{% url 'example:get_example' %}")
.controller('exampleCtrl', ['$scope', '$http', 'EXAMPLE_URL', exampleCtrl]);
function exampleCtrl($scope, $http, EXAMPLE_URL) {
$scope.examplePromise = $http.get(EXAMPLE_URL).then(function(response) {
return response.data;
});
}
指示:
angular.module('exampleModule')
.directive('exampleDirective', ['exampleFactory', 'STATIC_URL', '$http', '$window', exampleDirective]);
function exampleDirective(exampleFactory, STATIC_URL, $http, $window) {
return {
scope: {
title:'@?',
loadingImage:'@?',
},
restrict: 'AE',
templateUrl: STATIC_URL + 'example/example-template.html',
controller: "exampleCtrl",
link: function (scope, element, attrs) {
//add default options:
if (!scope.title) {
scope.title = 'Example Title';
}
if (!scope.loadingImage) {
scope.loadingImage = '';
}
scope.examplePromise.then(function(data) {
scope.exampleData = data;
// do something
});
}
};
}
有没有办法多次实例化一个指令,但不必在控制器中发出两次 Http GET 请求?
UPDATE这就是我所做的,我按照答案中的建议添加了一项服务。
Service:
angular.module('chRatingsModule')
.factory('chExampleFactory', ['$http', 'EXAMPLE_URL', chExampleFactory]);
function chExampleFactory($http, EXAMPLE_URL) {
var api = {}
var promise = null;
api.examplePromise = examplePromise;
function examplePromise() {
if (promise == null) {
promise = $http.get(EXAMPLE_URL).then(function(response) {
return response.data;
});
}
return promise;
}
return api;
}
更新指令:
angular.module('exampleModule')
.directive('exampleDirective', ['exampleFactory', 'STATIC_URL', '$http', '$window', exampleDirective]);
function exampleDirective(exampleFactory, STATIC_URL, $http, $window) {
return {
scope: {
title:'@?',
loadingImage:'@?',
},
restrict: 'AE',
templateUrl: STATIC_URL + 'example/example-template.html',
link: function (scope, element, attrs) {
exampleFactory.examplePromise.then(function(data) {
scope.exampleData = data;
// do something
});
}
};
}