Is there a way to make AngularJS load partials in

2019-01-02 16:44发布

I have a route setup like this:

var myApp = angular.module('myApp', []).
    config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        when('/landing', {
            templateUrl: '/landing-partial',
            controller: landingController
        }).
        when('/:wkspId/query', {
            templateUrl: '/query-partial',
            controller: queryController
        }).
        otherwise({
            redirectTo: '/landing'
        });
}]);

I want to be able to make angularjs download both the partials in the beginning and not when requested.

Is it possible?

标签: angularjs
8条回答
呛了眼睛熬了心
2楼-- · 2019-01-02 17:10

You can pass $state to your controller and then when the page loads and calls the getter in the controller you call $state.go('index') or whatever partial you want to load. Done.

查看更多
人气声优
3楼-- · 2019-01-02 17:12

Add a build task to concatenate and register your html partials in the Angular $templateCache. (This answer is a more detailed variant of karlgold's answer.)

For grunt, use grunt-angular-templates. For gulp, use gulp-angular-templatecache.

Below are config/code snippets to illustrate.

gruntfile.js Example:

ngtemplates: {
  app: {                
    src: ['app/partials/**.html', 'app/views/**.html'],
    dest: 'app/scripts/templates.js'
  },
  options: {
    module: 'myModule'
  }
}

gulpfile.js Example:

var templateCache = require('gulp-angular-templatecache');
var paths = ['app/partials/.html', 'app/views/.html'];

gulp.task('createTemplateCache', function () {
return gulp.src(paths)
    .pipe(templateCache('templates.js', { module: 'myModule', root:'app/views'}))
    .pipe(gulp.dest('app/scripts'));
    });

templates.js (this file is autogenerated by the build task)

$templateCache.put('app/views/main.html', "<div class=\"main\">\r"...

index.html

<script src="app/scripts/templates.js"></script>
<div ng-include ng-controller="main as vm" src="'app/views/main.html'"></div>
查看更多
登录 后发表回答