AngularJS - ng-include不适用于ng-view

时间:2014-08-06 14:53:58

标签: angularjs angular-services angularjs-ng-include ng-view

我有一个功能,可以在点击时包含html文件。问题是它在ng-view(使用$ routeProvider)下不起作用,而它在ng-view之外工作正常。我怀疑将include函数从控制器移动到服务可能有所帮助,但我不确定如何做到这一点,因为我是Angular的新手。

HTML工作时:

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

HTML不起作用时:

<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);  
    }
  })
}

上述“include”函数不适用于$ routeProvider。它在ng-view之外使用时工作正常,没有$ routeProvider。将'include'函数从mainCtrl移动到serrvice会有什么作用吗? 有什么提示吗?

由于

2 个答案:

答案 0 :(得分:0)

您的<ng-include src="'view/main.html'" >视图/ main.html ...

在您的路由器中有templateUrl: 'views/main.html' .. 你应该更正你的模板网址来查看/ main.html ..

答案 1 :(得分:0)

在main.html

 <div ng-controller="MyController">

和app.js

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

不同的控制者......