2015-09-29 71 views
2

我对AngularJs比较新,我有一个问题,当数据来自HTTP请求时使用自定义指令。AngularJs指令与HTTP请求数据

我有一个HTTP请求服务。

app.service('someService', function($http, $q){ 

    this.getData = function(){ 

     var deferred = $q.defer(); 
     $http({ 
      method: 'GET', 
      url: 'theUrl' 
     }) 
     .success(function(data, status){ 
      deferred.resolve(data); 
     }) 
     .error(function(data, status){ 
      deferred.reject; 
     }) 

     return deferred.promise; 
    } 

}) 

和一个调用服务的控制器。

app.controller('someConroller', function($scope, someService){ 

    someService.getData().then(function(response){ 

     $scope.data = response; 
    }) 

    $scope.someArrayData = [ 
       {.....}, {.....}, ... 
      ] 
} 

这是一个非常简单的自定义指令。

app.directive('customDirective', function(){ 

    return { 

     link: function(scope, element, attrs){ 

      console.log(scope[attrs['customDirective']]); 
     } 
    } 
}) 

的问题是,当我使用someArrayData指令的情况下正常工作。但是当我使用data(我从http服务获得的数据)获取指令的实例时,console.log(data)给了我未定义的内容。

<div custom-directive="someArrayData"></div><!-- console.log(scope[attrs['customDirective']]) gives the expected result --> 

<div custom-directive="data"></div><!-- console.log(scope[attrs['customDirective']]) undefined --> 

感谢您的帮助。

+0

是否HTTP响应包含在你所期望的格式所需的数据? –

+0

是的,它包含数据。 –

回答

4

你需要一个$watch“收听”你的指令内部的新的价值,一旦你的服务解决: 你可以简单地用NG-如果包裹的HTML元素。有很多种方法可以做到这一点,但这对于理解这个概念最直接。此外,如果您将自己的价值绑定到该指令的范围,您可能会清理这一点 - 本质上,您可以简化对scope[attrs[...的调用。遵守以下...

angular.module('app', []) 
.controller('ctrl', function($scope, $timeout) { 

    // -- simulate ajax call 
    $timeout(function() { 
     $scope.data = ['A', 'B', 'C']; 
    }, 500) 
}) 
.directive('customDirective', function() { 
    return { 
     scope: { 
      data: '=customDirective' 
     }, 
     link: function(scope, elem, attrs) { 

      scope.$watch('data', function(newVal, oldValue) { 
       console.log(newVal) // -- or console.log(scope.data) 
      }); 
     } 
    } 
}); 

JSFiddle Link - 演示

+0

感谢您的回答,您的解决方案应该可以工作,但它并不是我不知道为什么。由@Mohamed ElSaqqa提出的解决方案有效。 –

+0

记得使用'=' – scniro

+0

进行正确的作用域声明它在添加作用域时起作用。 –

-1

控制器和指令有不同的范围,所以当你在你的控制器中指定$scope.data时,你没有为你的指令做这件事。所以你应该在你的指令中注入你的服务并在那里请求数据。

如果您在理解范围方面存在问题,请在Angular documentation for scope中阅读。

我建议您下载Chrome的Angular JS Batarang扩展程序 - 它允许您检查页面上的所有不同范围。

+0

但视图中的{{数据}}绑定数据。 –

+0

这是因为视图绑定到控制器 - 但该指令有一个单独的子范围。尝试一下! – inorganik

+0

我会尝试一下,但是这样做,自定义指令将取决于服务而不是从视图注入的数据。它不可重用。 –

3

这是因为指令链接时数据尚未检索。

<div ng-if="data">  
<div custom-directive="data"></div> 
</div> 
+0

感谢您的回答,它工作正常,我不明白为什么像@ scniro提出的观察者不工作。 –

+0

@BillBilal的解决方案工作得很好。他的解决方案是基于观察附加在指令范围内的值,只要它发生变化,您就可以触发任何您想要的逻辑。 – melsaqqa