AngularJs 用 $location 设置和判断在哪个页面

之前有个判断在那个页面上的问题困扰了我很久~后来查了很久的文档才找到的$location这个注入的Service,和大家分享下拉~省的你们找啦~

当然可以用window.location来达到同样的目的

我是不是棒棒哒?~

前方高能。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

这是AngularJS 介绍$location的网址啦(想阅读先翻墙):https://docs.angularjs.org/guide/$location

言归正传。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。


直接看官网的例子吧


1>首先:这是Getter and setter 方法的使用。

// get the current path
$location.path();

// change the path
$location.path('/newValue')
也可以变形使用啦~

//Change multiple segments in one go, chain setters like this:

$location.path('/newValue').search({key: value});


2>Replace method(中文可能翻译成替代方法)

即,把原来的位置替换成别的

$location.path('/someNewPath');
$location.replace();
// or you can chain these as: $location.path('/someNewPath').replace();

3>对比window.location(必须有图有真相是吧,上图)

。。。。我懒得翻译了术语太多。。总之功能很强就对了。



4>什么时候需要用到$location呐?

Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser.

(任何时间当你的应用在现在的URL上需要改变和跳转的时候,或者你需要改变现在浏览器中的URL时候-----TnT,英语烂请见谅)


5>还有一个特性一定要介绍(上图)

这个。。。我暂时也不太懂,欢迎看了这篇文章而且懂的人来给我解答啦~(此处应该有掌声~)


6>最后的最后一定是小例子啦~加深一下记忆吧~

    Browser in HTML5 Fallback mode (Hashbang mode)

(1)index.html

<div ng-controller="LocationController">
  <div ng-address-bar></div><br><br>
  <div>
    $location.protocol() = <span ng-bind="$location.protocol()"></span> <br>
    $location.host() = <span ng-bind="$location.host()"></span> <br>
    $location.port() = <span ng-bind="$location.port()"></span> <br>
    $location.path() = <span ng-bind="$location.path()"></span> <br>
    $location.search() = <span ng-bind="$location.search()"></span> <br>
    $location.hash() = <span ng-bind="$location.hash()"></span> <br>
  </div>
  <div id="navigation">
    <a href="http://www.example.com/base/first?a=b">/base/first?a=b</a> |
    <a href="http://www.example.com/base/sec/ond?flag#hash">sec/ond?flag#hash</a> |
    <a href="/other-base/another?search">external</a>
  </div>
</div>
(2)app.js

angular.module('hashbang-mode', ['fake-browser', 'address-bar'])

.constant('initUrl', 'http://www.example.com/base/index.html#!/path?a=b#h')
.constant('baseHref', '/base/index.html')
.value('$sniffer', { history: false })

.config(function($locationProvider) {
  $locationProvider.html5Mode(true).hashPrefix('!');
})

.controller("LocationController", function($scope, $location) {
  $scope.$location = {};
  angular.forEach("protocol host port path search hash".split(" "), function(method){
    $scope.$location[method] = function(){
      var result = $location[method].call($location);
      return angular.isObject(result) ? angular.toJson(result) : result;
    };
  });
})

.run(function($rootElement) {
  $rootElement.on('click', function(e) {
    e.stopPropagation();
  });
});

(3)FakeBrowser.js

angular.module('fake-browser', [])

.config(function($provide) {
 $provide.decorator('$browser', function($delegate, baseHref, initUrl) {

  $delegate.onUrlChange = function(fn) {
     this.urlChange = fn;
   };

  $delegate.url = function() {
     return initUrl;
  };

  $delegate.defer = function(fn, delay) {
     setTimeout(function() { fn(); }, delay || 0);
   };

  $delegate.baseHref = function() {
     return baseHref;
   };

   return $delegate;
 });
});

(4)addressBar.js

angular.module('address-bar', [])
.directive('ngAddressBar', function($browser, $timeout) {
   return {
     template: 'Address: <input id="addressBar" type="text" style="width: 400px" >',
     link: function(scope, element, attrs){
       var input = element.children("input"), delay;

       input.on('keypress keyup keydown', function(event) {
               delay = (!delay ? $timeout(fireUrlChange, 250) : null);
               event.stopPropagation();
             })
            .val($browser.url());

       $browser.url = function(url) {
         return url ? input.val(url) : input.val();
       };

       function fireUrlChange() {
         delay = null;
         $browser.urlChange(input.val());
       }
     }
   };
 });

(5)protractor.js(测试JS)

it("should show fake browser info on load", function(){
  expect(addressBar.getAttribute('value')).toBe(url);

  expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
  expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
  expect(element(by.binding('$location.port()')).getText()).toBe('80');
  expect(element(by.binding('$location.path()')).getText()).toBe('/path');
  expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}');
  expect(element(by.binding('$location.hash()')).getText()).toBe('h');

});

it("should change $location accordingly", function(){
  var navigation = element.all(by.css("#navigation a"));

  navigation.get(0).click();

  expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/index.html#!/first?a=b");

  expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
  expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
  expect(element(by.binding('$location.port()')).getText()).toBe('80');
  expect(element(by.binding('$location.path()')).getText()).toBe('/first');
  expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}');
  expect(element(by.binding('$location.hash()')).getText()).toBe('');


  navigation.get(1).click();

  expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/index.html#!/sec/ond?flag#hash");

  expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
  expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
  expect(element(by.binding('$location.port()')).getText()).toBe('80');
  expect(element(by.binding('$location.path()')).getText()).toBe('/sec/ond');
  expect(element(by.binding('$location.search()')).getText()).toBe('{"flag":true}');
  expect(element(by.binding('$location.hash()')).getText()).toBe('hash');

});

(6)效果图一定要有的咯~

a.点击第一个链接

b.点击第二个链接

c.点击第三个链接

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。