首頁  >  問答  >  主體

angular.js - 已實作的angularjs專案用requirejs進行模組化時遇到問題

其實就是對todoMVC專案用requirejs進行模組化。原本的angularjs分別在controller、directive、service中分別定義了一個模組來代表這三者。
下面是directive:todoFocus.js

(function () {
    'use strict'
    angular.module('todoFocus',[]).directive('todoFocus',function ($timeout){
        return function (scope,element,attrs){
            scope.$watch(attrs.todoFocus,function (newVal){
                if(newVal){
                    $timeout(function(){
                        element[0].focus();
                    },0,false);
                }
            })
        }
    })
})()

上面就是一個directive。
之後在app.js中

(function () {
    'use strict';
    angular.module('todomvc', ['todoCtrl', 'todoFocus', 'todoStorage']);
})();

我用requirejs模組化之後directive變成了這樣:

(function () {
    'use strict'
    define(['angular'],function (angular) {
        angular.module('todoFocus',[]).directive('todoFocus',function ($timeout){
        return function (scope,element,attrs){
            scope.$watch(attrs.todoFocus,function (newVal){
                if(newVal){
                    $timeout(function(){
                        element[0].focus();
                    },0,false);
                }
            })
        }
    })
        return 'todoFocus';
    })
})()

然後app.js變成這樣:

(function () {
    'use strict';
    require(['angular'],function  (angular) {
        require([
            'controllers/todoCtrl',
            'directives/todoFocus',
            'services/todoStorage'
            ],function  (todoCtrl,todoFocus,todoStorage) {
                angular.module('todomvc',[todoCtrl,todoFocus,todoStorage]);
                angular.bootstrap(document, ['todomvc']);
            })
    })
})();

之後打開網頁發現所有的js檔案都載入出來了,但是並不能實現效果。 。

是不是app.js不能這麼寫。沒怎麼用過requireJS/(ㄒoㄒ)/~~

貼一下我的檔案路徑

下面是我的main.js

(function  (win) {
    'use strict';

    require.config({
        paths: {
            angular: '../node_modules/angular/angular'
        },
        shim: {              //专门用来配置不兼容的模块
            angular: {
            exports: 'angular'    //输出变量名,表示这个模块外部调用时的名称
            }
        },
        deps: ['app']     //deps数组,表示该模块依赖app模块,所以要先加载app模块
});
})(window)

感覺我的路徑沒啥問題呀/(ㄒoㄒ)/~~

phpcn_u1582phpcn_u15822684 天前491

全部回覆(1)我來回復

  • 巴扎黑

    巴扎黑2017-05-15 17:00:28

    模組依賴注入錯誤了,檢查下引用路徑

    回覆
    0
  • 取消回覆