Answer the question
In order to leave comments, you need to log in
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];
}
};
}
});
<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
You can then make a factory or a service and extract the methods you need from them.
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>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question