【发布时间】:2017-05-26 17:46:20
【问题描述】:
我对 Angular 1.x 的 ES6 语法/结构有点陌生,我遇到了将函数从父控制器传递到子控制器的问题。
这就是应用程序的绑定方式(我使用 webpack + babel 作为入口点):
const requires = [
'ngRoute',
];
//App
angular.module('kanban',requires)
.controller('dashboardCtrl', dashboardCtrl)
.component('board', board)
.component('task', task)
.config(routes);
在我的路线中,我只有一条路线,即我的“父母”
export default function($routeProvider) {
$routeProvider
.when('/', {
template: dashboardTemplate,
controller: 'dashboardCtrl',
controllerAs: '$ctrl',
});
}
谁的控制器如下所示:
export default function($rootScope) {
$rootScope.title = 'Kanban';
let _this = this;
this.boards = [
{
_id: 'b1',
title: 'backlog',
tasks: ['t1', 't2'],
}
];
this.deleteBoard = function(board) {
console.log(board);
let index = _this.boards.indexOf(board);
if (index !== -1) {
_this.boards.splice(index, 1);
}
};
并且在模板中,通过ng-repeat创建child,传入函数
<board ng-repeat="board in $ctrl.boards" board="board" onDelete="$ctrl.deleteBoard(board)" ></board>
并且板子将属性绑定为一个带有&的函数
export const board = {
template: boardTemplate,
controller: boardCtrl,
bindings: {
board: '=',
onDelete: '&',
}
};
并且该函数被添加到控制器中的不同函数中:
export default function boardCtrl() {
let _this = this;
this.deleteBoard = function(){
console.log(_this.onDelete);
_this.onDelete({board: _this.board});
};
}
然后点击调用:
<button ng-click="$ctrl.deleteBoard()"></button>
我可以访问板(子)控制器的功能,它会在控制台中打印:
function (locals) {
return parentGet(scope, locals);
}
并且没有返回错误,但是父 deleteBoard 函数中的 console.log 没有被调用。
这里发生了什么?为什么孩子似乎意识到它正在调用父范围内的某些东西,但没有到达它?
【问题讨论】:
-
可能是因为使用了相同的
$ctrl命名空间? -
@loan 我尝试了不同的
controllerAs:来更改命名空间,但不影响行为! -
你能在小提琴中重现这种行为吗?
标签: javascript angularjs ecmascript-6