0

Having an issue with trying to pass some scope data from my app controller to directive

http://plnkr.co/edit/github:plnkr/starters/v1.4.0/templates/angularjs?open=lib%2Fscript.js&deferRun=1&preview

(function () {
  'use strict';

  angular
    .module('app', [])
    .controller('HomeCtrl', ['$http', '$scope', HomeCtrl])
    .directive('services', [
      function () {
        return {
          restrict: 'E',
          scope: {
            testData: '='
          },
          template:
            '<h2 class="service-name">Test: {{testData}}</h2>' 
        };
      }
    ]);

  /**
   * Home controller.
   * @param {*} $scope
   */

  function HomeCtrl($http, $scope) {
    $scope.testData = 'name';

  }
})();

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="lib/style.css" />
    <script src="lib/script.js"></script>
  </head>

  <body ng-app="app">
    <div ng-controller="HomeCtrl">
      <services testData="testData"></services>
    </div>
  </body>
</html>

I'm getting undefined for the scope "=" variable, testData I can get it to render in the app using {{testData}}, but when passing it as an attribute, the directive is not receiving the value.

1 Answer 1

1

Here is your show code example modify to pass scope data to directive.

(function () {
  'use strict';

  angular
    .module('app', [])
    .controller('HomeCtrl', ['$http', '$scope', HomeCtrl])
    .directive('services', [
      function () {
        return {
          restrict: 'E',
          scope: {
            testData: '@testData'    //  ****************** note here 
          },
          template:
            '<h2 class="service-name">Test: {{testData}}</h2>' 
        };
      }
    ]);

  /**
   * Home controller.
   * @param {*} $scope
   */

  function HomeCtrl($http, $scope) {
    $scope.testData = 'name';

  }
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

  <body ng-app="app">
    <div ng-controller="HomeCtrl">
      <!--  //  ****************** note here  -->
      <services test-Data="Hello World!"></services>
    </div>
  </body>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.