Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

angularJS 怎么把controllers.js里面的controller拆分成一个个独立的js文件?

情况是这样的:
这个controllers.js 文件中写了很多组件的controller。我想把组件的controller都拆分,分别放入对应的js里面,例如,下面的homeCtrl,我就想放入一个homeCtrl.js里面,这该怎么操作?
我按照github里面很多人的angularjs项目的文件去分,失败了。

`var app = angular.module('app', ['ngCookies', 'ui.router', 'ngFileUpload', 'tm.pagination']);
//路由配置
app.config(function($stateProvider, $urlRouterProvider){
   $stateProvider
   .state("home",{
 url: '/home',
 cache: false,
 template: '<div class="container"><div class="jumbotron"><h1></h1></div></div>',
 controller: "homeCtrl"
 })
   $urlRouterProvider.otherwise("home");
})

//清除templateUrl缓存
 app.run(function($rootScope, $templateCache){
        $rootScope.$on('$locationChangeStart', function(event, next, current){
         if(typeof(current) !== 'undefined'){
          console.log(current);
          $templateCache.remove(current);
          $templateCache.remove(current.templateUrl);
      }
      })
 })

 // 组件controller
 app.controller('homeCtrl', function ($http, $scope,$state, TipService) {
 
 // xxxxxxxxxxxx
 })
 
 .
 .
 .
 ...`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这个问题我是后来收到一个答友的启发,使用ocLazyLoad,自己摸索成功的,现在放出我的解决方案:

.state("home",{
 url: '/home',
 cache: false,
 template: '<div class="container"><div class="jumbotron"><h1></h1></div></div>',
 controller: "homeCtrl",
 resolve: {
        loadMyService: ['$ocLazyLoad', function($ocLazyLoad) {
            return $ocLazyLoad.load('assets/js/component/home.js');  // 按需加载js
        }]
     }
 })
 
 // home.js
angular.module('app').controller('homeCtrl', function(){})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...