在指令之间共享范围 - 缺少$http

Sharing scope between Directives - missing $http

本文关键字:缺少 http 范围 指令 之间 共享      更新时间:2023-09-26

这是我的两个指令。我基本上想在他们之间分享范围。但是,我得到了一个未定义的$http错误。我知道我需要把$http放在某个地方,但是在哪里呢?

aresAnalytics.directive('market', function($http) {
    return {
        restrict: 'E',
        controller: function ($scope, Data) {
            $scope.data = Data;
        },
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                console.log("A1 " + attrs.market);
                scope.temp = attrs.market;
                $http.get('get_markets').success(function(markets) {
                    Data.markets =  markets;
                });
            })
        }
    }
});
aresAnalytics.directive('events', function($http) {
   return {
       restrict: 'E',
       controller: function ($scope) {
           scope = $scope;
       },

       link: function(scope, element) {
           element.bind('click', function() {
               console.log(scope.temp);
           });
       }
   }
});

.HTML:

    <market ng-repeat="market in data.markets" market="{{ market }}">
        {{ market }}
    </market>

另外,我认为我这样做的方式

 $http.get('get_markets').success(function(markets) {
        Data.markets =  markets;
});

不正确,我可以用它替换什么。

而且,我应该改用隔离范围"@"吗?那会是什么样子?

感谢您阅读本文!

您需要

像这样注入$http服务。

app.directive('something', function( $http ) { ... });

角度依赖注入

要访问这样的属性,有很多方法,但这是一种简单的方法。

将 html 更改为

  <market ng-repeat="market in data.markets" market="market">
        {{ market }}
  </market>

需要像这样解析

app.directive('something', function( $http, $parse ) { ... });

并像这样获取您的属性

scope.temp = $parse(attrs.market)(scope);

通过这种方式,您可以直接从范围获取它,而另一种方式,angular 尚未呈现该属性。

问题出在您的依赖注入上。试试这个:

aresAnalytics.directive('market', ['$http', function($http) {
    // (you code)
}]);

或者,如果您不使用代码简化器/丑化器:

aresAnalytics.directive('market', function($http) {
    // (you code)
});
我不知道

,但我只需要在我的作用域附加一个$parent即可始终使用父作用域。(比如用scope.$parent代替scope)。

参考: https://github.com/angular/angular.js/wiki/Understanding-Scopes