【问题标题】:AngularJS - ng-include doesn't work on ng-viewAngularJS - ng-include 不适用于 ng-view
【发布时间】:2014-09-29 13:54:30
【问题描述】:

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

上述“包含”功能不适用于 $routeProvider。在没有 $routeProvider 的情况下在 ng-view 之外使用时可以正常工作。将“包含”功能从 mainCtrl 移动到服务可以解决问题吗? 有什么建议吗?

谢谢

【问题讨论】:

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


    【解决方案1】:

    你的&lt;ng-include src="'view/main.html'" &gt;view/main.html...

    在你的路线中有templateUrl: 'views/main.html'.. 您应该将您的模板网址更正为 view/main.html..

    【讨论】:

    • 谢谢,但这只是一个错字,我的网址是正确的。
    【解决方案2】:

    在 main.html 中

     <div ng-controller="MyController">
    

    在 app.js 中

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

    不同的控制器....

    【讨论】:

    • 对不起,这是另一个错字,我故意更改了一些 ctrls。这里的命名没有问题。
    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2016-11-13
    • 2014-06-08
    • 2014-06-15
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多