【问题标题】:How can I use both $http and $timeout in AngularJS directive?如何在 AngularJS 指令中同时使用 $http 和 $timeout?
【发布时间】:2016-08-25 10:32:19
【问题描述】:

这是我的代码的一部分

Object_Angular.directive("ntgChangeScanInnerHtmlWorkshop", ["$timeout", function($timeout){ ...

但我还需要访问$http,因为我想从我的 API 加载内容。我该怎么做?

我所拥有的是_ids 在<p></p> 中的显示。假设我有<p>{{collections._id}}</p>。我希望 <p></p> 显示名称字段 (collections.String_Name) 而不是 _id。所以我想在值加载后获取<p>{{collections._id}}</p>的内部HTML,然后通过{ _id: innerHTMLValueOfP }从API获取String_Name,然后在.success中我确实用result.String_Name设置了内部值。因此,我需要在我的指令中包含 $http$timeout 来实现这一点。

【问题讨论】:

  • 分享正确的代码,有助于理解问题。
  • 您似乎知道如何注入服务,所以我不明白您的问题。
  • 不确定您是否只是在寻找这个,但您不能只输入["$timeout", "$http", function($timeout, $http){ ... 吗?你的问题有点难以理解。

标签: angularjs http angularjs-directive timeout


【解决方案1】:

在指令中使用 $http 的示例

app.directive('myTag', ['$http', function($http) {
   return {
      restrict: 'E',
      transclude: true,
      replace: true,     
      scope:{
      src:"="       
    },
   controller:function($scope){
    console.info("enter directive controller");
    $scope.gallery = [];

   console.log($scope.src);

    $http({method: 'GET', url:$scope.src}).then(function (result) {
                       console.log(result);                              
                    }, function (result) {
                        alert("Error: No data returned");
                    });
        } 
    }
 }]);
 or
 app.directive('example', function( $http){
   return {
      restrict:'E',
      link: function($scope,$element,$timeout){

            $http.post('/example', {
                data
            }).success(function(data){
            }).error(function(data){});
        }
   });    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多