main.js中定義好設定項
requirejs.config({
paths: {
jQuery: '../lib/jquery.min',
angular: '../lib/angular.min',
angularRouter: '../lib/angular-route.min',
angularAnimate: '../lib/angular-animate.min',
ngNotify: '../lib/angular-atomic-notify',
api: '../js/common/api',
utils: '../js/common/utils'
},
shim: {
'angular': {
deps: ['jQuery'],
exports: 'angular'
},
angularRouter: {
deps: ['angular'],
exports: 'ngRoute'
},
angularAnimate: {
deps: ['angular']
},
ngNotify: {
deps: ['angular']
},
api: {
deps: ['angular']
},
utils: {
deps: ['angular']
}
}
});
// 手动开启angular服务
require(['angular', 'app'], function(angular){
angular.element(document).ready(function(){
angular.bootstrap(document, ['yceMain']);
});
});
app中定義模組與路由
app.js
define(['angular', 'angularRouter', 'ngNotify', 'angularAnimate', 'api', 'utils'], function(angular){
var yceMain = angular.module('yceMain',['ngRoute', 'atomic-notify', 'ngAnimate']);
yceMain.config(['$routeProvider', '$controllerProvider', function ($routeProvider, $controllerProvider){
$routeProvider
.when('/dashBoard', {
templateUrl: 'views/dashBoard.html'
})
.when('/appManage', {
templateUrl: 'views/appManage.html',
controller: 'appManage'
})
}]);
return yceMain;
});
appManage controller.js程式碼如下
define(['app'], function (yceMain){
yceMain.controller('appManage', ['$scope' , function ($scope){
$scope.aa = 11;
}]);
});
頁面報錯
Error: [ng:areq] http://errors.angularjs.org/1.5.0/ng/areq?p0=appManage&p1=not%20aNaNunction%2C%20got%20undefined
若在app.js中定義appManage controller,則視圖中可以拿到數據,但如果在appManage controller.js 使用define(['app'],xx) 取得angular.module則取不到,求解。
我想大声告诉你2017-05-15 17:10:36
define(['app'], function (yceMain){
yceMain.controller('appManage', ['$scope' , function ($scope){
$scope.aa = 11;
}]);
});
這個app應該是沒有被注入進去的,你console.log(yceMain)一下。
如果你只是想將appManage這個控制器綁定到app這個模組裡面,應該可以這麼寫:
// appManage controller.js
angular.module('app')
.controller('appManage', ['$scope' , function ($scope){
$scope.aa = 11;
}]);
當然,這個controller也要引入到頁面裡面去的
我之前是用ui-router + oclazyload
某草草2017-05-15 17:10:36
已解決,問題在於angular在開啟ng-app服務之前,要把所以的controller,service都要註冊完成。
但是我的想法是要非同步載入controller,透過require。
function ctrlRegister (ctrlName, ctrlModule) {
return function ($q) {
var defer = $q.defer();
require(ctrlModule, function (controller) {
$controllerProvider.register(ctrlName, controller);
defer.resolve();
});
return defer.promise;
}
}
該函數完美解決問題,感謝/a/11...。