为什么我的指令没有在我的AngularJS应用中显示?

问题描述 投票:1回答:1

我刚刚在名为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正在成功加载。见下文

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9mS01VbS5wbmcifQ==” alt =“在此处输入图像描述”>

[我应该提一下,如果将指令代码放在控制器后的main.js中,并在['components']之后将mmApp作为参数传递,我将看到指令代码有效。这是更改后的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无法在包含我的components指令的helloWorld模块中成功调用? app.js无法连接到helloWorldz.js,这是否可能是问题?

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

javascript angularjs angularjs-directive gruntjs angularjs-module
1个回答
1
投票

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

angular.module('components')

而不是

angular.module('components',[])

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

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

© www.soinside.com 2019 - 2024. All rights reserved.