【问题标题】:AngularJS Passing Scope Data From App Controller to DirectiveAngularJS将范围数据从应用控制器传递到指令
【发布时间】:2021-09-28 11:12:19
【问题描述】:

尝试将一些范围数据从我的应用控制器传递到指令时遇到问题

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}} 让它在应用程序中呈现,但是当它作为属性传递时,指令没有接收到值。

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多