[英]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.