AngularJS 将范围数据从 App Controller 传递到指令

AngularJS Passing Scope Data From 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>

我对范围“=”变量 testData 未定义 我可以使用 {{testData}} 让它在应用程序中呈现,但是当它作为属性传递时,指令没有收到值。

这是您的显示代码示例,修改为将范围数据传递给指令。

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