我使用es6样式实现了角度项目,如下所示:
controller.js
export default class InsertController {
constructor($scope) {
this.$scope =$scope;
this.data=[];
}
fillGrid(data) {
console.log(data);
}
}
InsertController.$inject = ['$scope'];
Directive.js
import angular from 'angular';
function FanGrid($compile) {
return {
replace: true,
restrict: 'E',
transclude: true,
link: function (scope, element, attrs) {
//I want access to fillGrid method of controller
scope.fillGrid(data);
}
}
}
export default angular.module('directives.fanGrid', [])
.directive('fanGrid', FanGrid)
.name;
现在我想知道
fillGrid()
方法
"this"
醇>
答案 0 :(得分:0)
您可以使控制器属于指令本身,因此它们具有共享范围。
import angular from 'angular';
import directiveController from 'directive.controller.js';
export default () => ({
bindToController: {
someBinding: '='
},
replace: true,
restrict: 'E',
link: function (scope, element, attrs) {
// To access a method on the controller, it's as simple as you wrote:
scope.vm.fillGrid(data);
},
scope: true,
controller: directiveController,
controllerAs: 'vm'
});
然后你的控制器就像你写的那样:
export default class directiveController {
constructor($scope) {
this.$scope = $scope;
this.data = [];
}
fillGrid(data) {
console.log(data);
}
}
答案 1 :(得分:0)
如果你在angular1中使用ES6,你最好实现这样的指令:
class FanGridController {
constructor() {
this.fillGrid('some data') //Output some data
}
}
function FanGridDirective($compile) {
return {
replace: true,
restrict: 'E',
transclude: true,
controller: "FanGridController",
scope: {
fillGrid: "=?fillGrid",
controllerThis: "=?controllerThis"
}
link: function(scope, element, attrs) {
//I want access to fillGrid method of controller
},
controllerAs: "vm",
bindToController: true
}
}
export { FanGridController, FanGridDirective }
通过此实现,this
指向FanGridController
中的“vm”。 vm
是$scope
对象的属性。 scope:{}
您的问题的答案是您可以将fillGrid和controllerThis作为范围参数,并将其传递给HTML模板。然后使用this.fillGrid
调用此方法。
export default class InsertController {
constructor($scope) {
this.$scope = $scope;
this.data = [];
}
fillGrid(data) {
console.log(data);
}
}
InsertController.$inject = ['$scope'];
传递HTML中的参数
<fan-grid fill-grid="vm.fillGrid" controller-this="vm"></fan-grid>
然后调用方法并在指令控制器中访问控制器:
class FanGridController {
constructor() {
let controllerThis = this.controllerThis;
this.fillGrid('some data'); //Output some data
}
}
或链接功能:
link: function(scope, element, attrs) {
let controllerThis = $scope.vm.controllerThis;
$scope.vm.fillGrid('some data') //Output some data
}