GVKun编程网logo

AngularJS:打开html5mode(true)时,相对链接路径被破坏(javascript 打开链接)

14

本文将为您提供关于AngularJS:打开html5mode(true)时,相对链接路径被破坏的详细介绍,我们还将为您解释javascript打开链接的相关知识,同时,我们还将为您提供关于Angula

本文将为您提供关于AngularJS:打开html5mode(true)时,相对链接路径被破坏的详细介绍,我们还将为您解释javascript 打开链接的相关知识,同时,我们还将为您提供关于Angular1位置html5mode等效于angular2、Angularjs $location html5mode浅析、AngularJS 1.2.0 ngBindHtml和trustAsHtml不能与ngModel一起使用、AngularJS HTML5Mode的实用信息。

本文目录一览:

AngularJS:打开html5mode(true)时,相对链接路径被破坏(javascript 打开链接)

AngularJS:打开html5mode(true)时,相对链接路径被破坏(javascript 打开链接)

我一直在寻找,我找到了解决这个问题的“解决方案”,但我仍然无法使其正常工作.

场景:

我正在使用UI路由器构建一个Angular(版本1.2)网站,并在localhost上的Node服务器上运行它.我试图让它与$locationProvider一起使用“漂亮”的url并打开html5(true).点击它我的网站工作正常,但当我尝试导航到相对链接路径或刷新链接路径时,页面中断.我还打算在完成后将此webapp部署到Heroku:

相对链接路径:

http://localhost:8000/locksmith-services

PAGE输出结果

Cannot GET /locksmith-services

我采取的步骤:

1.)在我的“index.html”< head>,我已将我的基本网址设置为:

<base href="/"></base>

2.)在我的app.js文件中(对于Angular),我写了如下:

// App Starts
angular
    .module('app',[
        'ui.router','ngAnimate','angular-carousel'
    ])
    .config(['$urlRouterProvider','$stateProvider','$locationProvider',function($urlRouterProvider,$stateProvider,$locationProvider) {
        $urlRouterProvider.otherwise("/");

        $stateProvider
            .state('home',{
                url: '/',templateUrl: 'pages/home.html',controller: 'homeCtrl'
            })
            .state('services',{
                url: '/locksmith-services',templateUrl: 'pages/locksmith-services.html',controller: 'servicesCtrl'
            })
            .state('locations',{
                url: '/locksmith-locations',templateUrl: 'pages/locksmith-locations.html'
            })
            .state('payment',{
                url: '/locksmith-payment',templateUrl: 'pages/locksmith-payment.html'
            })
        // use the HTML5 History API
        $locationProvider.html5Mode(true);
    }])

3.)在我的导航中,我将我的html写成:

<div>
    <a ui-sref="home">
        <img src="images/logo.png"https://www.jb51.cc/tag/logo/" target="_blank">logo" alt="Austin Texas Locksmith" />
    </a>
</div>
<nav>
    <aui-sref="services" ui-sref-active="active">Services</a>
    <aui-sref="locations" ui-sref-active="active">Locations</a>
    <aui-sref="payment" ui-sref-active="active">Payment</a>
</nav>

4.)我的server.js文件(节点服务器)

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/front'));
var port = process.env.PORT || 8000;
app.listen(port);

什么是最好的解决方案?在此先感谢您的帮助.

解决方法

感谢@trehyu帮助我得到这个答案.

就像他写的那样,我需要在我的server.js文件上设置一些设置,将用户重定向到我的“index.html”文件.

所以取决于你的文件结构……

之前(不工作)

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/front'));
var port = process.env.PORT || 8000;
app.listen(port);

之后(工作)

var express = require('express');
var app = express();

app.use('/js',express.static(__dirname + '/front/js'));
app.use('/build',express.static(__dirname + '/../build'));
app.use('/css',express.static(__dirname + '/front/css'));
app.use('/images',express.static(__dirname + '/front/images'));
app.use('/pages',express.static(__dirname + '/front/pages'));

app.all('/*',function(req,res,next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('/front/index.html',{ root: __dirname });
});

var port = process.env.PORT || 8000;
app.listen(port);

我希望这有助于其他人!

Angular1位置html5mode等效于angular2

Angular1位置html5mode等效于angular2

我试图找到我可以在angular2中启用 html5mode的地方.不幸的是,无法从文档或任何地方找到它.我正在使用gulp和browser-sync来加载我的文件.
我见过很多人说使用connect-modrewrite之类的东西

browserSync.instance = browserSync.init({
    server: {
      baseDir: ['app'],middleware: [
        proxyMiddleware,modRewrite([
          '^[^\\.]*$/index.html [L]'
        ])
      ]
    },});

我设置它,但它仍然无法工作,我得到404除了主要网址之外的任何东西.
这有什么线索吗?

解决方法

您正在寻找的是 PathLocationStrategy,这是默认的LocationStrategy

注意

使用此功能时,您需要将服务器设置为将所有请求重定向到根URL.例如,如果您的用户请求myApp.com/someRoute,则将从该网址解析资产,这是不正确的.相反,您希望服务器提供index.html页面而不管指定的路由,但仍保持路由完整,以便客户端应用程序可以使用它.

另外一定要设置你的< base path =“/”/>标记在HTML的头部.

Angularjs $location html5mode浅析

Angularjs $location html5mode浅析

关于HTML5 history API

参考资料:http://diveintohtml5.info/history.html
参考资料为英文,内容较为简单,周末会做简单翻译,方便英语吃力的童鞋。

H5之前,一个URL对应一个页面,无论以何种方式修改地址栏地址,都会导致页面完全刷新,无论跳转页面之间是否有关联。简单来说,H5的history API提供接口,可以使用javascript修改地址栏路径,而不刷新页面。

使用场景

简化说明:未设置静态缓存。

假设后端数据输出模式为:获取数据---读取模板---渲染模板。不同页面之间共享模板,只是数据内容不同。在没有H5的新接口之前,不同页面之间的跳转,则相同的脚本,CSS文件会重新加载,不仅加剧服务器压力,在慢速网络下,用户体验也会变差。在有H5接口之后,不同路径跳转,可以拦截超链接默认行为,通过脚本控制地址栏,通过Ajax加载数据,在前端完成数据呈现,就能避免不必要的资源加载时间。

Demo浅析

  • 数据源
    /static/articles/index.json;
    /static/articles/node.json;
    /static/articles/javascript.json
json// index.json
{
  "title": "Frontend develop language",
  "content": "FE encounter lots of trouble"
}
// node.json
{
  "title": "Node theme develop",
  "content": "whether believe or not, node changes frontend develop way"
}
// javascript.json
{
  "title": "Javascript theme develop",
  "content": "maybe javascript just tools, it enhance programmer skill"
}
  • 模板
    /views/article.jade
    (临时看的jade,所以简单为上)
jadedoctype html
html
  head
     title Shuffle History
     script(src="/libs/superagent.js")
     script(src="/js/initialize.js") 
  body
     h3#title
       | #{title}
     p#content
       | #{content}
     p
       a(href="/") Index entrance
     p
       a(href="/node/" id="node") Node entrance
     p
       a(href="/javascript/" id="javascript") Javascript entrance

总计三个页面,共享同一个jade模板。数据源对应关系为
/ ---------- index.json
/node/ --- node.json
/javascript --- javascript.json

若直接访问/,/node/, javascript页面,express读取对应数据源,渲染模板,然后直接输出html,代码如下:

javascript/**
 * Created by jasonborn on 14/11/19.
 */
var jade = require(''jade'');
var path = require(''path'');
var express = require(''express'');
var app = express();
app.set(''env'', ''development'');
app.engine(''jade'', jade.__express);

app.get(''/'', function(req, res) {
  res.render(''article.jade'', require(''./static/articles/index.json''), function(err, html) {
    res.type(''html'');
    res.send(html);
  })
});

app.get(''/node/'', function(req, res) {
  res.render(''article.jade'', require(''./static/articles/node.json''), function(err, html) {
    res.type(''html'');
    res.send(html);
  })
});

app.get(''/javascript/'', function(req, res) {
  res.render(''article.jade'', require(''./static/articles/javascript.json''), function(err, html) {
    res.type(''html'');
    res.send(html);
  })
});

app.use(express.static(path.join(__dirname, ''static'')));

app.listen(1336);

自此实现所谓的MVC模式,然后使用H5 history API,所有的页面都会加载initilize.js脚本文件:

javascript/**
 * Created by jasonborn on 14/11/20.
 */

window.onload = function() {
  var title = document.querySelector(''#title'');
  var content = document.querySelector(''#content'');
  var node = document.querySelector(''#node'');
  var javascript = document.querySelector(''#javascript'');
  var resolveContent = function(target) {
    switch (true) {
      case target === ''/'':
            target = ''/articles/index.json'';
            break;
      case /node/.test(target):
            target = ''/articles/node.json'';
            break;
      case /javascript/.test(target):
            target = ''/articles/javascript.json'';
            break;
    }

    superagent
        .get(target)
        .end(function(err, res) {
          title.textContent = res.body.title;
          content.textContent = res.body.content;
        })
  };

  window.history.replaceState({
    "target": window.location.pathname
  }, null, ''./'');

  window.onpopstate = function(event) {
    resolveContent(event.state.target);
  };

  node.addEventListener(''click'', function(event) {
    event.preventDefault();

    window.history.pushState({
      "target": "/node/"
    }, null, ''/node/'');

    resolveContent(''/node/'');

    window.onpopstate = function(event) {
      resolveContent(event.state.target);
    };
  });

  javascript.addEventListener(''click'', function(event) {
    event.preventDefault();

    window.history.pushState({
      "target": "/javascript/"
    }, null, ''/javascript/'');

    resolveContent(''/javascript/'');

    window.onpopstate = function(event) {
      resolveContent(event.state.target);
    };
  });
};

pushState修改地址记录,onpopstate表示通过后退方式退回pushState后的路径时,执行何种操作。这里是通过Ajax请求拉取数据,然后呈现数据(较大型项目可能会使用前后端模板引擎来渲染,例如x-template)。

Angularjs $location html5mode

开启html5mode,通过config来配置即可。

javascriptangular.module(''shuffleApp'', [''ngRoute'', ''ngSanitize''])
    .config([''$routeProvider'', ''$locationProvider'', function($routeProvider, $locationProvider) {
        $routeProvider
            .when(''/love'', {
                template:''<a href="/hate">To hate</a><p ng-bind="love"></p>'',
                controller: ''LoveCtrl''
            })
            .when(''/hate'', {
                template: ''<a href="/love">To love</a><p ng-bind="hate"></p>'',
                controller: ''HateCtrl''
            })
            .otherwise(''/love'');
        $locationProvider.html5Mode(true);
    }]);

上述配置,在加载入口文件之后,地址栏会变为http://hostname/love,而不是http://hostname/#/love。但是存在一个问题,后者可以直接访问,前者也许能访问,也许不能,但不会出现预期的结果,典型结果就是NG中文API站,每次向在新页面打开某个链接,结果就是华丽丽的报错,例如:http://docs.angularjs.cn/api,所以需要做重定向:

javascriptapp.get(''/love'', function(req, res) {
    res.sendFile(path.join(__dirname, ''static/index.html''));
});

具体的重定向上会导致路径设计上的一些问题,所以需要注意。

联系方式

QQ: 491229492
github: https://github.com/bornkiller

AngularJS 1.2.0 ngBindHtml和trustAsHtml不能与ngModel一起使用

AngularJS 1.2.0 ngBindHtml和trustAsHtml不能与ngModel一起使用

我觉得这应该很容易,因为我使用ngBind HtmlUnsafe与Angular 1.0.8完美配合.我在api文档和StackOverflow上阅读了我现在需要使用带有ngBindHtml的$sce.trustAsHtml(),但我似乎无法让它工作.

这基本上是我在阅读的内容中使用的格式:

var myApp = angular.module('myApp',[]);

function myController($scope,$sce){
    $scope.myHtml = $sce.trustAsHtml($scope.sourceText);
}

HTML:

<html ng-app="myApp">

  <head>
    <script data-require="angular.js@1.2.0-rc3" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="myController">
      <textarea ng-model="sourceText"></textarea>

      <div ng-bind-html="myHtml"></div>
    </div>
  </body>

</html>

我认为这将是直截了当的,但我一定是错的,错过了一些东西.

我把这个简单的例子放到了Plunker:http://plnkr.co/edit/ZX4dONBlzv1X8BcO1IBV?p=preview

解决方法

这是你在找什么?
http://plnkr.co/edit/IZkzsuKHvbYiyV07CGqp

// would strongly suggest including sanitize in your scripts and injecting it
// into your app here to prevent "unsafe as safe" errors
var myApp = angular.module('myApp',['ngSanitize']);

myApp.controller('myController',['$scope','$sce',function myController($scope,$sce){
  $scope.myHtml = "initial";  //not needed,for testing

  $scope.changeText = function() {
    $scope.myHtml = $sce.trustAsHtml($scope.sourceText);
  }
}]);

HTML:
    
    

<head>
    <script data-require="angular.js@1.2.0-rc3" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
    <script src="http://code.angularjs.org/1.2.0-rc.3/angular-sanitize.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="myController">
      <textarea ng-model="sourceText" ng-change="changeText()"></textarea>

      <div ng-bind-html="myHtml"></div>
    </div>
  </body>

</html>

AngularJS HTML5Mode

AngularJS HTML5Mode

我在我的角应用程序中使用HTML5模式来关闭hashbangs,这是因为我将为我的用户提供以下URL:

http://myapp.com/nicklewis

而不是:

http://myapp.com#/nicklewis

后者有效,但它不适合虚荣URL.

由于没有编写我自己的NodeJS应用程序来解决这个问题,Firebase中是否可以使用或不使用?

Firebase刚刚有一个包含此功能的最新更新.您可以在firebase.json中使用它:
"rewrites": [ {
    "source": "**","destination": "/index.html"
} ]

这是他们的文档中使用的代码示例,并将任何未找到的目录或文件发送回index.html.

请务必注意,您需要将firebase部署工具更新为version 1.1.0 or higher才能使其正常工作:

$npm update -g firebase-tools

根据您的权限,您可能需要使用“sudo”.

您可以在此处阅读文档:https://www.firebase.com/docs/hosting/guide/url-redirects-rewrites.html

您可以在此处阅读有关更新firebase工具的信息:https://www.firebase.com/docs/hosting/guide/command-line-tool.html

关于AngularJS:打开html5mode(true)时,相对链接路径被破坏javascript 打开链接的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Angular1位置html5mode等效于angular2、Angularjs $location html5mode浅析、AngularJS 1.2.0 ngBindHtml和trustAsHtml不能与ngModel一起使用、AngularJS HTML5Mode的相关信息,请在本站寻找。

本文标签: