Angular.js在控制器中调用指令函数

时间:2014-11-07 16:24:20

标签: javascript angularjs angularjs-directive

我想调用指令中定义的函数,与this stackoverflow question

相反

我尝试了这个但是没有用。

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.someDirectiveFn = function(arg) {
                 return "in directive";
            };
        },
    }
});

function MyCtrl($scope) {
    alert($scope.someDirectiveFn());
}

这可能吗?我怎么能得到它?这是一种不好的做法吗?

修改

我有这样的方式:

.controller('MyCtrl', function($scope) {
    alert($scope.func());
})

.directive('myDirective', function() {
    return {
      controller: function($scope, $element){
        $scope.func = function() {
          return "text";
         };
      }
    }
});

3 个答案:

答案 0 :(得分:3)

您可以使用事件系统来实现这一目标。

首先,使用参数在作用域上发出自定义事件。 其次,使用angular $ on方法监听指令中的范围。

app.controller('MyCtrl', function($scope) {
  $scope.invokeDirectiveMethod = function() {
    $scope.$emit('invokeMyDirectiveMethod', 'myParameter');
  };
})

.directive('myDirective', function() {
  return {
    link: function(scope, element, attrs) {
      var someDirectiveFn = function(event, arg) {
        alert(arg + " in directive");
      };

      scope.$on('invokeMyDirectiveMethod', someDirectiveFn);
    },
  }
});

这是一个有效的plunker

<强>更新

根据您的更新,事件通信不适合您的问题。

如何使用双向绑定将对象传递给指令并在该对象中定义 someDirectiveFn ?这样你就可以传递参数并从中返回值。

app.controller('MyCtrl', function($scope) {
  $scope.shareObject = {};

  $scope.invokeDirectiveMethod = function() {
    if (angular.isFunction($scope.shareObject.someDirectiveFn)) {
      $scope.message = $scope.shareObject.someDirectiveFn('from controller'); 
    }
  };
})

.directive('myDirective', function() {
  return {
    scope: {
      'shareObject': '='
    },
    link: function(scope, element, attrs) {
      scope.shareObject.someDirectiveFn = function(arg) {
        return arg + ' from parameter';
      };
    },
  }
});

更新了plunker

答案 1 :(得分:1)

你没有发布你的html代码,所以我假设你的自定义指令是在MyCtrl中使用的。由于执行函数的时间,这不起作用。

控制器功能始终在链接功能之前执行。

  

Here是关于差异的很酷的文章。

因此,如果您希望控制器能够在指令中调用函数,您可以广播事件(例如在halilb的答案中)或使指令监听特定的范围值,如下所示:

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.$watch("message", function() { console.log(message); });
        },
    }
});

function MyCtrl($scope) {
    $scope.message = "Hello Directive";
}

答案 2 :(得分:0)

我猜你想拥有一个在指令和控制器之间共享的功能吗?

如果是这样的情况如何创建服务并将服务注入指令和ctrl。这样你只需要创建一次。

  app.service('sharedFucntionService', function() {
     return {
        someFn : function (arg) {
             alert(arg + " in directive")  
        }
    }
 });

将服务注入指令

 app.directive('myDirective',function( sharedFucntionService){
  return {
        link: function (scope, element, attrs) {
            // do something with sharedFucntionService
        }
    }

});

也将服务注入控制器    function MyCtrl($ scope,sharedFucntionService){         ......    }

相关问题