V
V
Viktor2017-02-15 19:28:45
JavaScript
Viktor, 2017-02-15 19:28:45

How to call a controller method outside a component?

How can I make the addRandomEmail() method execute when the button is clicked?
angular version 1.6

<body ng-app="App">
   <my-componentr></my-component>
   <button ng-click="addRandomEmail()">test</button>
</body>

angular.module('myComponent').
  component('myComponent', {
    template: `
     <div class="editor">
    {{$ctrl.email}}
   </div>`,
    controller: function myController() {
      this.email = '';
      this.randomEmails = [
        '[email protected]',
        '[email protected]',
        '[email protected]',
        '[email protected]',
        '[email protected]',
        '[email protected]'
      ];
      this.addRandomEmail = function () {
        let random = Math.random() * this.randomEmails.length;
        random = Math.floor(random);

        this.email = this.randomEmails[random];
      }
    };
  }
  });

UPD
It turned out to run.
Thanks SergeyBugai for the link
Maybe you can implement it better if you write like that.
<body ng-app="App" ng-controller="parentCtrl">
   <my-componentr></my-component>
   <button ng-click="RandomEmail();">test</button>
</body>

angular.module('myComponent').
   component('myComponent', {
      template: `
     <div class="editor">
    {{$ctrl.email}}
   </div>`,
      controller: function myController() {
         this.email = '';
         this.randomEmails = [
            '[email protected]',
            '[email protected]',
            '[email protected]',
            '[email protected]',
            '[email protected]',
            '[email protected]'
         ];
         this.addRandomEmail = function () {
            let random = Math.random() * this.randomEmails.length;
            random = Math.floor(random);

            this.email = this.randomEmails[random];
         }
      };

      $scope.addRandomEmail = this.addRandomEmail;
      $scope.randomEmails = this.randomEmails;
      $scope.email = this.email;

      $scope.$on('randomEmail', function (event, fromParent) {
         $scope.addRandomEmail();
      });
   }
  });

angular.module('emailsEditor').controller('parentCtrl', function ($scope) {
  $scope.randomEmail = function () {
    $scope.$broadcast('randomEmail');
  }
});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
RTW, 2017-02-15
@RTW

You can then make a factory or a service and extract the methods you need from them.

S
Severus256, 2017-02-15
@severus256

Through the directive ng-controller does not work?
Type:

<body ng-app="App" ng-controller="myController">
   <my-componentr></my-component>
   <button ng-click="addRandomEmail()">test</button>
</body>

S
SergeyBugai, 2017-02-15
@SergeyBugai

Why not create a button in a component?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question