【问题标题】:AngularJS ng-include do HistoryJS stop workingAngularJS ng-include 做 HistoryJS 停止工作
【发布时间】:2014-01-16 11:00:40
【问题描述】:

在我开始使用 ng-include 之前,我的代码一直有效。现在,每次我转到使用此指令的页面时,我都会卡在页面上。后退按钮已停止工作,您将永远停留在同一页面的循环中。

我的网站使用 Asp.NET MVC 5 运行。

我的一些代码:

HTML“主机”

<div id="place">
    <div data-ng-include="'/app/angular/views/place.html'"></div>
</div>

HTML place.html

<div>
    <h1>{{place.PlaceName}}</h1>
    <ul class="unstyled-list">
        <li data-ng-repeat="hint in place.Hints">
            <!-- more code -->
        </li>
    </ul>
</div>

JAVASCRIPT

$scope.place = { };

// 'maps' is a google maps plugin 
maps.autoComplete({ success: function(result) {
    // gets the result of the user search
    History.pushState({ name: result.name, id: result.id }, result.name, '/place/' + result.id);
});

History.Adapter.bind(window, 'statechange', function () { 
    var state = History.getState(); 

    // go to the server and get more info about the location
    $mapService.getMetaInfo({id: state.data.id}).then(function (d) {
        // get place info
        $scope.place = d;
    });
});

当我删除 ng-include 并将其替换为“原始”html 时,它可以正常工作。这种“无限循环”只有在添加ng-include 时才会发生。

【问题讨论】:

  • 我猜你应该展示你是如何使用ng-include指令的,如果你使用得当,你应该提供一个能重现问题的插件。
  • 您应该将任何外部插件转换为 Angular 指令,将两种不同的范式混合用于 DOM 操作是不明智的。
  • 我无法想象有人会这样做。如果它是一个简单的插件,我会同意你的看法,但是,任何插件......它太重了,你不觉得吗?
  • @LeCoder 实际上你不应该。 Angular Team 的目标之一是与其他工具的兼容性。我同意 Stewie 的观点 - 如果没有真正的代码,我们无法回答您的问题。由于place.html模板中的ng-include,我只能猜测无限循环。
  • 你可以这样做,这样我们就可以看到路径没有任何问题..
    并用

标签: angularjs history.js


【解决方案1】:

当您在 ng-include 指令中设置模板 url 时,指定的模板会被 angular 调用,然后将其放入 angular $templateCache,然后该内容会在视图上呈现。如果你下次调用它,它会直接从 angular $templateCache 中获取。我希望您将该模板放在 angularrun 阶段的 templateCache 中(在 angular 运行它编译周期之前。) 我建议你在 Angular 启动时加载该模板。

在页面上加载 Angular 之前(即在 Angular 配置阶段之后)将此模板放在您的 Angular $templateCache

代码

angular.module('app',[]).
config(function(){
  //configuration code will be here.
}).
run(function($templateCache,$http){
  //run block will run write after the config phase
  $http.get('/app/angular/views/place.html',{ cache : $templateCache }
});

在此模板将在 $templateCache 中可用后,无需为模板制作任何 ajax。

希望这不会导致任何无限循环。就像你目前面临的问题一样。

谢谢。

【讨论】:

  • @Le Coder 我的回答对你有帮助吗?
【解决方案2】:

我曾经遇到过这个问题, 好像是Html5模式。

尝试将其添加到您的应用配置中:

$locationProvider.html5Mode(false);

【讨论】:

    【解决方案3】:

    将您的代码放在 setTimeout 中,因为当您使用 ng-include 时,需要几英里的时间来加载 html 并附加到具有 ng-include 的 div。

    setTimeout(function{
    // write your code here
    },100)
    

    【讨论】:

    • 认为回调是比超时更可靠的解决方案。如果网络延迟使请求持续 101 毫秒或 200 毫秒怎么办?也许你可以得到这个请求的 Promise 并传递一个成功的回调。
    猜你喜欢
    • 2013-08-29
    • 2021-09-17
    • 2013-12-01
    • 2015-02-20
    • 2017-12-05
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多