角度访问"这个"来自指令范围的受控类

时间:2017-03-06 12:32:52

标签: javascript angularjs angularjs-directive ecmascript-6

我使用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;

现在我想知道

  1. 如何在指令
  2. 中访问和调用控制器的fillGrid()方法
  3. 如何从指令
  4. 访问控制器类的"this"

2 个答案:

答案 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:{} 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>

然后调用方法并在指令控制器中访问控制器:

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
}