将 AngularJS 中的 $http 服务传递给正常的 javascript 函数
Pass $http service in AngularJS to normal javascript function
我在 AngularJS 指令中使用 Jquery 小部件。
App.directive('eff',['$http',function($http) {
function link(scope, element, attrs) {
$('#Widget').charts(
getWidget(),
function (chart) {
// generate chart widget...
}
});
}
return {
restrict: 'E',
link: link
};
}]);
// Normal JS function
function getWidget(){
// return widget data
}
现在我想在 getWidget
函数中使用 $http
服务表单 AngularJS 从服务器加载数据。
是否可以将 $http
服务对象传递给 getWidget
方法并加载数据?
感谢@Gant,您可以尝试一下。
function getWidget(){
var $http = angular.injector(['ng']).get('$http');
$http.get("path"); //
}
您可以获得这样的服务。这将减少由于多个 angular 个实例
而可能发生的错误数量
function getService(param) {
//use the root angular element id over here
var applicationEl = angular.element('[YourRootElementReference]'),
myInjector;
param = '$http';
if (applicationEl) {
try {
myInjector = applicationEl.injector(); //this will fetch you the injector
if (myInjector) {
return myInjector.get(param); // return the service
}
} catch (e) {
return undefined;
}
}
function doStuff(){
angular.element(document).injector().invoke(function($compile , service1 , $http) {
//do remainder of the stuff here
});
}
希望对您有所帮助
我在 AngularJS 指令中使用 Jquery 小部件。
App.directive('eff',['$http',function($http) {
function link(scope, element, attrs) {
$('#Widget').charts(
getWidget(),
function (chart) {
// generate chart widget...
}
});
}
return {
restrict: 'E',
link: link
};
}]);
// Normal JS function
function getWidget(){
// return widget data
}
现在我想在 getWidget
函数中使用 $http
服务表单 AngularJS 从服务器加载数据。
是否可以将 $http
服务对象传递给 getWidget
方法并加载数据?
感谢@Gant,您可以尝试一下。
function getWidget(){
var $http = angular.injector(['ng']).get('$http');
$http.get("path"); //
}
您可以获得这样的服务。这将减少由于多个 angular 个实例
而可能发生的错误数量function getService(param) {
//use the root angular element id over here
var applicationEl = angular.element('[YourRootElementReference]'),
myInjector;
param = '$http';
if (applicationEl) {
try {
myInjector = applicationEl.injector(); //this will fetch you the injector
if (myInjector) {
return myInjector.get(param); // return the service
}
} catch (e) {
return undefined;
}
}
function doStuff(){
angular.element(document).injector().invoke(function($compile , service1 , $http) {
//do remainder of the stuff here
});
}
希望对您有所帮助