0

我在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方法并加载数据?

+0

即使,该功能可能无法返回同步远程服务器获取数据。虽然检查Angular文档的'inject'。 – Gant

+0

为什么你需要这样做,为什么你不能在角度范围内保持该功能.. ?? – harishr

+0

@entre我不明白你刚刚提出的问题。你的意思是将该功能绑定到AngularJS应用程序('App')?像** App.getWidget(//代码在这里)** –

回答

0

感谢@Gant这里是你可以尝试的。

function getWidget(){ 
    var $http = angular.injector(['ng']).get('$http'); 
    $http.get("path"); // 
    } 
+0

这是不正确的。 – Gant

+0

你的意思是你可以在角度应用外使用角度的http服务?为什么不发布答案呢?也许那时我也可以学习新的东西。 –

+0

@Gant阅读本文档并注意文档 $ inject属性注释 为了允许缩小器重命名函数参数并仍能够注入正确的服务,该函数需要使用$ inject属性进行注释。 $ inject属性是要注入的服务名称的数组。 [也是这个答案](http://stackoverflow.com/questions/18698963/use-of-inject-in-angular-js-in-controllers) –

0

你可以得到这样的服务。这将可能发生的错误的数量减少因多角度实例

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; 
     } 
    } 
0
function doStuff(){ 
     angular.element(document).injector().invoke(function($compile , service1 , $http) { 
      //do remainder of the stuff here   
     }); 
} 

我希望这有助于