Calling directive's methods from parent controller in AngularJS

后端 未结 5 1123
无人及你
无人及你 2021-02-03 22:59

I am using AngularJS with the alias controllers pattern. I can\'t access (or I don\'t know how to) directive methods from a parent controller.

I have a

5条回答
  •  时光说笑
    2021-02-03 23:42

    You are isolating the scope when you write:

     scope: {
           text: '='
         },
    

    Here's a slightly modified version of your code, this time, lets you call directive method. Mostly I just got rid of 'scope' in directive, and changed it to using $scope in the controller, rather than this, and Alias pattern..

    WARNING: This might not reflect the correct behavior, with regard's to which variables get changed, but answers your question by showing how you can access directive's method from controller. This is usually not a good design idea..

    http://codepen.io/anon/pen/azwJBm

    angular.module('myApp', []).
    
    controller('MyCtrl', function($scope){
      var that = this;
    
      $scope.text = 'Controller text';
    
      $scope.dirText = 'Directive text';
    
      $scope.click = function(){
        $scope.changeText();
      }
    }).
    
    directive('myDir', function(){
      return {
         restrict: 'E',
        /* scope: {
           text: '='
         },*/
         link: function(scope, element, attrs){
           scope.changeText = function(){
             scope.text = 'New directive text';
           };
         },
         template: '

    {{text}}

    ' }; });

    {{text}}

提交回复
热议问题