简体   繁体   English

带有HTTP请求数据的AngularJs指令

[英]AngularJs directive with HTTP request data

I'm relatively new to AngularJs, I have a problem using a custom directive when data comes from an HTTP request. 我是AngularJ的新手,当数据来自HTTP请求时,我在使用自定义指令时遇到问题。

I have a service with an HTTP get request. 我有一个带有HTTP get请求的服务。

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;
    }

})

and a controller that calls the service. 以及调用该服务的控制器。

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

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

        $scope.data = response;
    })

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

Here is a very simple custom directive. 这是一个非常简单的自定义指令。

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

    return {

        link: function(scope, element, attrs){

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

The problem is when I get an instance of the directive using someArrayData it works fine. 问题是当我使用someArrayData获取指令的实例时,它可以正常工作。 But when I get an instance of the directive using data (the data that I get from the http service) console.log(data) gives me undefined. 但是当我使用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 -->

Thanks for helping. 感谢您的帮助。

You'll need a $watch to "listen" for that new value inside your directive once resolved by your service. 一旦您的服务解决了问题,您将需要一个$watch来“监听”指令中的新值。 There are various ways to do this, but this will be the most straightforward for understanding the concept. 有多种方法可以执行此操作,但这将是理解该概念最直接的方法。 Also, you can likely clean this up a bit if you bind your value to that directives scope - essentially your call to scope[attrs[... can be streamlined. 另外,如果您将值绑定到该指令范围,则可能会稍微清理一下-本质上scope[attrs[...可以简化对scope[attrs[...调用。 Observe the following... 注意以下几点...

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 - demo JSFiddle Link-演示

That's because the data is not yet retrieved when the directive is linked. 这是因为链接该指令时尚未检索数据。 You can simply wrap the html element with ng-if: 您可以简单地用ng-if包装html元素:

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

The controller and the directive have different scopes, so when you assign $scope.data in your controller, you aren't doing it for your directive. 控制器和指令的作用域不同,因此,当在控制器中分配$scope.data时,就不会为指令使用它。 So you should inject your service in your directive and request the data there. 因此,您应该在指令中注入服务并在那里请求数据。

If you are having trouble understanding scope heirarchies, read up on them in the Angular documentation for scope . 如果您在理解合并范围层次结构时遇到困难,请在Angular文档中阅读有关合并范围的内容

I would suggest downloading the Angular JS Batarang extension for Chrome - it allows you to inspect all the different scopes on your page. 我建议下载适用于Chrome的Angular JS Batarang扩展-它使您可以检查页面上的所有不同范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM