AngularJS-ng-include在ng-view上不起作用 [英] AngularJS - ng-include doesn't work on ng-view

查看:89
本文介绍了AngularJS-ng-include在ng-view上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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起作用的时间:

HTML when it works:

<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:

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.在没有$ routeProvider的ng-view外使用时,它可以正常工作.将"include"功能从mainCtrl移到服务中会成功吗? 有提示吗?

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?

谢谢

推荐答案

在main.html

In main.html

 <div ng-controller="MyController">

和在app.js中

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

不同的控制器......

different controllers....

这篇关于AngularJS-ng-include在ng-view上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆