Home Accessing variables set in the controller from the directive
Reply: 1

Accessing variables set in the controller from the directive

Rudy M
1#
Rudy M Published in 2018-02-13 21:55:01Z

I am trying to avoid the use of $scope in my angular controller (as suggested in a best practices tutorial). In the controller, I'm setting testVariable. In the directive, I'm returning the template, including testVariable, but this added variable does not output any value. This code is based on what I've found in the AngularJS documentation.

Below is my javascript code:

(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);

Here is the 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>

I set up a plunkr for this here.

Bulkan
2#
Bulkan Reply to 2018-02-13 22:59:51Z

If you use controllerAs and bindToController it will simplify your directive and then access 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
    };
  });

You can further simplify your directive if you use .component to create docsSimpleDirective

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.351438 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO