【问题标题】:How to call angular component function from out side directives如何从外部指令调用角度分量函数
【发布时间】:2017-03-21 15:07:02
【问题描述】:

我正在使用 angularjs 1.5.8,我使用 group 模块将组件名称创建为 Group,同样我创建了与名为 scroll 的组件相同的模块的指令, 我需要调用组件函数 loadmoregroups 来调用 api 以在启动时滚动获取更多组。

    angular.module('group', []).
        component('group', {
            templateUrl: '/djangotemplates/private/group/list.html',
            controller: function(
                    $cookies,
                    $http,
                    $location,
                    $scope,
                    Flash,
                    $animate,
                    Group,
                    $timeout,
                    $rootScope
                ){

                $rootScope.loadMoreGroups =function()
                {
                    alert("loadmore");
                }
        }
}).directive('scroll', function() {
    return {
        restrict: 'A',
        link: function(rootScope, element, attrs, $window, $scope, $document) {
            var bind = element.bind('tbody');
            var raw = element[0];
            angular.element(bind).on("scroll", function() {
                //console.log('in scroll mode');

                if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {

                    **rootScope.loadMoreGroups();** //unable to call this `enter code here`function

                }
            });
        }
    };
});

【问题讨论】:

标签: angularjs


【解决方案1】:

我不知道这是否是最好的方法,但您可以使用广播从子组件调用父组件。

 if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
     $scope.$broadcast("call_func")
 }

组件

.component('group', {
    templateUrl: '/djangotemplates/private/group/list.html',
    controller: function(
        $cookies,
        $http,
        $location,
        $scope,
        Flash,
        $animate,
        Group,
        $timeout,
        $rootScope
    ) {
        $rootScope.loadMoreGroups = function() {
            alert("loadmore");
        }
        $scope.$on("call_func", function(ev) {
            $rootScope.loadMoreGroups()
        })
    }
})

【讨论】:

  • 很好,如果这有帮助,请务必标记为正确答案:D
猜你喜欢
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多