[英]Angular access to “this” of controlled class from directive scope
我用es6样式实现了angular项目,如下所示:
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"
您可以使控制器属于指令本身,因此它们具有共享作用域。
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);
}
}
如果在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
是$scope
对象的属性。 而在所有的变量scope:{}
可以通过访问this
您问题的答案是,您可以将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>
然后调用该方法并在指令控制器中访问控制器的this:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.