在 angular 1.5 组件中使用 $emit [英] Using $emit in angular 1.5 component
本文介绍了在 angular 1.5 组件中使用 $emit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 angular 1.5 组件,并且需要从子组件中的 $emit 时调用父控制器中的函数.我们如何做到这一点?
I am using angular 1.5 component and need to call function in parent controller from when $emit in child component. How we can do this?
示例:
(function (angular) {
'use strict';
controllerName.$inject = [];
function controllerName() {
var _this = this;
function toBeCalledOnEmit() {//some code}
var vm = {
toBeCalledOnEmit: toBeCalledOnEmit
}
angular.extend(_this, vm);
}
angular.module('moduleName', [
]).component('parentComponenet', {
templateUrl: 'templateUrl',
controller: 'controllerName'
}).controller('controllerName', controllerName);
})(angular);
子组件:
(function (angular) {
'use strict';
childController.$inject = [];
function childController() {
//needs $emit here
}
angular.module('childModuleName', [
]).component('childComponent', {
templateUrl: 'templateUrl',
controller: 'childController'
}).controller('childController', childController);
})(angular);
推荐答案
我更喜欢使用单独的事件服务来公开订阅和通知功能.但是如果你更喜欢从子组件发出,那么它看起来像这样:
I prefer working with a separate event service that exposes subscribe and notify functions. But if you prefer to emit from the child component then it would look like this:
(function (angular) {
'use strict';
function childController($scope) {
$scope.$emit("someEvent", args);
}
angular.module('childModuleName', [
]).component('childComponent', {
templateUrl: 'templateUrl',
controller: ['$scope', childController]
});
})(angular);
父组件
(function (angular) {
'use strict';
function controllerName($scope) {
var _this = this;
function toBeCalledOnEmit(event, args) {
//some code
}
$scope.on('someEvent', toBeCalledOnEmit);
var vm = {
toBeCalledOnEmit: toBeCalledOnEmit
}
angular.extend(_this, vm);
}
angular.module('moduleName', [
]).component('parentComponent', {
templateUrl: 'templateUrl',
controller: ['$scope', controllerName]
});
})(angular);
这篇关于在 angular 1.5 组件中使用 $emit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文