简体   繁体   中英

AngularJS Passing Scope Data From App Controller to Directive

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM