为什么我的角度工厂没有加载?

时间:2014-03-23 19:18:15

标签: angularjs angularjs-factory angularjs-module

示例... Plunker

addon.js:

(function () {
  'use strict';
 angular.module('jzAddons', [])
  .factory('jzThemeFac', function () {
    return {
      themes:[
        {
          name: 'none',
          url: '',
          margin: '8px',
          bg: '#ffffff'
        },
        {
          name: 'amelia',
          url: '//netdna.bootstrapcdn.com/bootswatch/3.1.0/amelia/bootstrap.min.css',
          margin: '6px',
          bg: '#108a93'
        }
      ],

      changeTheme: function (theme) {
        var oldLink = angular.element('#bootstrapTheme');
        oldLink.remove();
        if (theme.name !== 'none') {
          var head = angular.element('head');
          head.append('<link id="bootstrapTheme" href="' + theme.url + '" rel="stylesheet" media="screen">');
        }
        currentTheme = theme;
      }
    };
  });

})();

app.js:

var app = angular.module('example', ['jzAddons']);

(function () {
  'use strict';

  app.controller('MainCtrl', ['jzThemeFac', function ($scope, jzThemeFac) {
    $scope.themes = jzThemeFac.themes;  /* Error comes from this line */
  }]);

})();

在我身体标签的底部,我有:

<script src="addon.js"></script>
<script src="app.js"></script>

我一直收到错误:

TypeError: Cannot read property 'themes' of undefined

2 个答案:

答案 0 :(得分:0)

您的工厂注入错误,您可以这样做:

app.controller('MainCtrl', ['$scope', 'jzThemeFac', function ($scope, jzThemeFac) {...

或只是:

app.controller('MainCtrl', function ($scope, jzThemeFac) {

编辑:您也可以移动:

(function () {
    'use strict';  

到文件的开头

答案 1 :(得分:0)

你需要记住将$ scope注入你的MainCtrl。所以app.js应该是这样的:

var app = angular.module('example', ['jzAddons']);

(function () {
  'use strict';

  app.controller('MainCtrl', ['$scope', 'jzThemeFac', function ($scope, jzThemeFac) {
    $scope.themes = jzThemeFac.themes;  /* Error comes from this line */
  }]);

})();