从指令访问控制器中设置的变量

时间:2018-02-13 21:55:02

标签: angularjs angularjs-directive angularjs-scope

我试图避免在我的角度控制器中使用$ scope(,如最佳实践教程中所述)。在控制器中,我设置了 testVariable 。在指令中,我将返回模板,包括 testVariable ,但此添加的变量不会输出任何值。此代码基于我在AngularJS文档中找到的内容。

以下是我的javascript代码:

(function(angular) {
  'use strict';
  angular.module('docsSimpleDirective', [])
    .controller('Controller', ['$scope', function($scope) {
      var _controller = this;

      $scope.customer = {
        name: 'Naomi',
        address: '1600 Amphitheatre'
      };

      _controller.testVariable = "Test Variable!"
    }])
    .directive('myCustomer', function() {
      return {
        template: 'Name: {{customer.name}}<br />Address: {{customer.address}}<br />Value Here: {{ testVariable }}'
      };
    });
})(window.angular);

这是HTML:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Example - example-directive-simple-production</title>

    <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body ng-app="docsSimpleDirective">
    <div ng-controller="Controller">
      <div my-customer></div>
    </div>
  </body>
</html>

我为此here设置了一个plunkr。

1 个答案:

答案 0 :(得分:1)

如果您使用controllerAsbindToController,则会简化您的指令,然后访问testVariable

angular.module('docsSimpleDirective', [])
  .controller('Controller', [function () {
    this.customer = {
      name: 'Naomi',
      address: '1600 Amphitheatre'
    };

    this.testVariable = "Testing data here!"
  }])
  .directive('myCustomer', function () {
    return {
      template: 'Name: {{$ctrl.customer.name}}<br />Address: {{$ctrl.customer.address}}<br />Value Here: {{ $ctrl.testVariable }}',
      controller: 'Controller',
      controllerAs: '$ctrl',
      bindToController: true
    };
  });

如果您使用.component创建docsSimpleDirective

,则可以进一步简化您的指令