我正在使用angular 1.5组件,并且需要在子组件中的$ emit时调用父控制器中的函数。我们怎么做到这一点?
示例:
(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);
答案 0 :(得分:11)
我更喜欢使用公开订阅和通知功能的单独事件服务。但是如果您希望从子组件中发出,那么它将如下所示:
(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);
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
答案 1 :(得分:3)
代码如下:
子组件:
(function (angular) {
'use strict';
childController.$inject = ['$scope'];
function childController($scope) {
//needs $emit here
$scope.$emit("topic-123", 'any message');
}
angular.module('childModuleName', [
]).component('childComponent', {
templateUrl: 'templateUrl',
controller: 'childController'
}).controller('childController', childController);
})(有角度的);
父组件:
(function (angular) {
'use strict';
controllerName.$inject = ['$scope'];
function controllerName($scope) {
var _this = this;
function toBeCalledOnEmit() {//some code}
var vm = {
toBeCalledOnEmit: toBeCalledOnEmit
}
$scope.$on('topic-123', function(event, msg) {
// @TODO
toBeCalledOnEmit();
});
angular.extend(_this, vm);
}
angular.module('moduleName', [
]).component('parentComponenet', {
templateUrl: 'templateUrl',
controller: 'controllerName'
}).controller('controllerName', controllerName);
})(有角度的);
答案 2 :(得分:2)
你可以使用$ rootScope这样做。它适用于我的情况 -
子组件:
(function (angular) {
'use strict';
childController.$inject = ['$rootScope'];
function childController($rootScope) {
$rootScope.$emit('myEvent',$scope.data)
}
})(angular);
父组件:
(function (angular) {
'use strict';
controllerName.$inject = ['$rootScope'];
function controllerName($rootScope) {
var _this = this;
function toBeCalledOnEmit() {//some code}
var vm = {
toBeCalledOnEmit: toBeCalledOnEmit
}
$rootScope.$on('myEvent', function(event, msg) {
toBeCalledOnEmit();
});
angular.extend(_this, vm);
}
})(angular);