AngularJS - ng-include doesn't work on ng-view

2019-08-05 06:35发布

问题:

I have a function to include html files on click. The problem is that it doesn't work when under ng-view (using $routeProvider), while it works fine outside of ng-view. I suspect that moving the include function from controller to service might help, but I am unsure how to do that as I'm new to Angular.

HTML when it works:

<body ng-app="MyApp">
    <ng-include src="'views/main.html'" ng-controller="mainCtrl"></ng-include>
</body>

HTML when it doesn't work:

<body ng-app="MyApp">
    <div ng-view></div>
</body>

main.html:

 <div ng-controller="mainCtrl">
    <button ng-click="include('temp1.html')">Block 1</button><i ng-click="delete('temp1.html')">DEL 1</i>

    <button ng-click="include('temp2.html')">Block 2</button><i ng-click="delete('temp2.html')">DEL 2</i>

    <button ng-click="include('temp3.html')">Block 3</button><i ng-click="delete('temp3.html')">DEL 3</i>

    <div ng-repeat="template in templates">
      <div ng-include="template.url">Content from blocks goes here</div>
    </div>
  </div>

APP.js:

   angular
  .module('MyApp', [
    'ngResource',
    'ngRoute',
    'ui.bootstrap'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'mainCtrl'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

mainCtrl:

angular.module('MyApp').controller('mainCtrl', function ($scope) {

$scope.templates=[];

$scope.include = function(templateURI) {
   var template={url:templateURI};
   $scope.templates.push(template);
   console.log($scope.templates);
}

$scope.delete= function(url){
  removeEntity($scope.templates,url);
}

var removeEntity = function(elements,url){
  elements.forEach(function(element,index){
    if(element.url===url){
      elements.splice(index,1);  
    }
  })
}

The above "include" function does not work with $routeProvider. It works fine when used outside the ng-view, without $routeProvider. Would moving the 'include' function from mainCtrl to the serrvice would do the trick? Any tips?

Thanks

回答1:

your <ng-include src="'view/main.html'" > view/main.html...

and in ur route there is templateUrl: 'views/main.html'.. you should correct ur template url to view/main.html..



回答2:

In main.html

 <div ng-controller="MyController">

and in app.js

$routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'mainCtrl'
      })

different controllers....