[英]How to get the last part of url AngularJS
How to build the function in AngularJS to chceck the last part of the url?如何在 AngularJS 中构建函数来检查 url 的最后一部分?
My examples:我的例子:
#/menu1/123/edit
#/menu2/444/create/new
#/menu3/sumbenu1/333/create/new
#/menu4/submenu2/subsubmenu1/subsubsubmenu1/543/edit
The thing is:事情是:
123
444
333
543
are the ID's which are generated outside Angular 123
444
333
543
是在 Angular 之外生成的 ID
I need to check the last parts of my url: /edit
or /create/new
.我需要检查我的 url 的最后部分: /edit
或/create/new
。
The length of the url will be different (number of /
inside url). url的长度会有所不同(url的数量/
内部)。
I have a controller in Angular to get the url:我在 Angular 中有一个控制器来获取网址:
.controller('urlCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) {
$rootScope.location = $location;
$scope.hashPath = "#" + $rootScope.location.path().toString();
}]);
I'm adding the #
character to the url because later I'm comparing it with my JSON.我将#
字符添加到 url 中,因为稍后我将它与我的 JSON 进行比较。
I tried this solution but it didn't work (I also checked another solutions from this topic and nothing happened).我尝试了这个解决方案,但它没有用(我还检查了这个主题的另一个解决方案,但什么也没发生)。
Any ideas?有任何想法吗?
EDIT:编辑:
Or how to check just the edit
or create
inside the url?或者如何只检查 url 中的edit
或create
?
My solution is:我的解决办法是:
var path = $location.path();
var multisearch = path.search(/create|edit|new/);
console.log("multisearch: " + multisearch);
This should give you the desired result:这应该会给你想要的结果:
window.alert(window.location.href.substr(window.location.href.lastIndexOf('/') + 1));
You could get the current URL by using: window.location.href Then you only need to get the part after the last '/'您可以使用以下方法获取当前 URL: window.location.href 然后您只需要获取最后一个 '/' 之后的部分
More efficient way:更有效的方法:
location.pathname.split('/').slice(-1)[0]
In case of http://example.com/firstdir/seconddir/thirddir?queryparams#hash
;在http://example.com/firstdir/seconddir/thirddir?queryparams#hash
情况下; it will give you thirddir
它会给你thirddir
pathname
will keep only the part of url after domain name and before query params pathname
名将只保留域名之后和查询参数之前的 url 部分split
will explode the url into array separated by /
split
会将 url 分解为由/
分隔的数组slice
will give you array containing only the last item slice
会给你只包含最后一项的数组[0]
will you last item as a string (in contrast to item of an array) [0]
您将最后一个项目作为字符串(与数组的项目相反)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.