AngularJs动态加载页面

时间:2016-01-12 22:18:40

标签: angularjs ajax dynamic

如何制作动态ajax加载页面功能?

我不想宣布所有的路线'像这样

angular.module('myApp', ['ngRoute'])
.config(function($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'views/main.html',
      controller: 'MainCtrl'
    })
    .when('/day/:id', {
      templateUrl: 'views/day.html',
      controller: 'DayCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });
})

我希望能够使用1个具有此功能的函数加载文件;

<a href="myLinkToFile" ng-click="loadPage()">
loadPage function(){
 var url = "get the HREF of the element that is clicked"
 load the file and put it in a div
 and prevent default click of the <a>

}

2 个答案:

答案 0 :(得分:1)

也许你应该试试这个

angular.module('myApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/', {
  templateUrl: 'views/main.html',
  controller: 'MainCtrl'
})
.when('/day/:id', {
  templateUrl: 'views/day.html/'+$routeParams.id+"/",
  controller: 'DayCtrl'
})
.otherwise({
  redirectTo: '/'
});
})
function DayCtrl($scope, $http) {
$scope.number=1

$scope.routeTo = function(id) {
window.location = "/day/"+id;
$scope.number+=1

} 
})

<强> HTML

<div ng-controller="DayCtrl">
<span ng-click="routeTo(number)">
Go to next page
</span>
<div ng-view >
</div>

</div>

}

答案 1 :(得分:0)

在Angular中,您必须在init app之前声明所有路由。我认为你的愿望是防止在第一个init中加载许多资源文件。如果我接受了您的想法,您可以尝试ocLazyModule来优化加载文件的性能