【问题标题】:Why is my directive not being seen in my AngularJS app?为什么在我的 AngularJS 应用程序中看不到我的指令?
【发布时间】:2013-05-28 11:30:52
【问题描述】:

我刚刚在一个名为 helloWorldz.js 的文件中创建了一个指令,该文件如下所示:

'use strict';

angular.module('components')
  .directive('helloWorld', function () {
    return {
      restrict : 'E',
      template : '<span>Hello World</span>'
    };
});     

包含我的路线的我的app.js 文件如下所示:

'use strict';

angular.module('mmApp', ['components'])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/designs', {
        templateUrl: 'views/designs.html',
        controller: 'MainCtrl'
      })
      .when('/blog', {
        templateUrl: 'views/blog.html',
        controller: 'MainCtrl'
      })   
      .otherwise({
        redirectTo: '/'
      });
  });    

我的控制器main.js 没有完成看起来像这样:

'use strict';

angular.module('mmApp', [])
  .controller('MainCtrl', function ($scope) {
    $scope.designTiles = [
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
    ];
  });

Chrome 开发工具告诉我helloWorldz.js 正在成功加载。见下文

我应该提到,如果我将我的指令代码放在我的控制器之后的 main.js 中,并在 mmApp 之后传递 ['components'] 作为参数,我将看到我的指令代码工作。这是更改后的main.js 控制器:

'use strict';

angular.module('mmApp', ['components'])
  .controller('MainCtrl', function ($scope) {
    $scope.designTiles = [
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
      { imageURL : "", title : "IMAGE" },
    ];
  });

angular.module('components', [])
  .directive('helloWorld', function () {
    return {
      restrict : 'E',
      template : '<span>Hello World</span>'
    }
});  

为什么app.js 没有成功调用包含我的helloWorld 指令的components 模块?这是app.js 无法连接到helloWorldz.js 的可能问题吗?

我还应该提到我正在使用 grunt 来编译所有内容。

【问题讨论】:

    标签: javascript angularjs angularjs-directive gruntjs angularjs-module


    【解决方案1】:

    看起来指令代码在独立版本中略有不同。有:

    angular.module('components')
    

    而不是

    angular.module('components',[])
    

    解决这个问题(通过将参数添加到独立版本)应该可以解决问题。我想很多人都遇到过这个问题,因为AngularJS's module page 上的最高评论是:

    本文档应警告“angular.module('myModule', [])” 总是创建一个新模块,但“angular.module('myModule')”总是 检索现有引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多