2017-01-10 37 views
0

我有和昨天一樣的問題:我需要通過AngularJS在HTML頁面中使用來自URL的參數。我的錯誤是什麼?通過HTML中的變量使用URL參數AngularJS

我需要顯示和使用參數,如:

https://url.com/index.html?user 

我需要該「用戶」,但現在不工作,沒有錯誤,現在,沒有什麼,其實,只是一個只有@的空h1。 :(

<div class="container" id="body-container" ng-controller="myController as myApp"> 
    <h1 id="header-username">@{{myApp.user}}</h1> 
</div> 

我應該做點別的?

(function() { 

    var app = angular.module('MyApp', ['ngRoute']); 

    app.controller('myController', function ($scope, $location) { 
     this.user = $location.search(); 
    }); 
})(); 

回答

0

爲$位置服務的默認行爲是在hashbang mode工作。在這種模式下,search()方法返回後面的參數?只有#存在於url中。

http://url.com/index.html#/?user 

由於您的網址沒有#,因此search()不會返回任何內容。

你可以嘗試使用HTML5 mode,它不需要#出現在url中。在這種情況下,search()返回{「user」:true}。

http://url.com/index.html/?user 

使用HTML5模式,配置$ locationProvider如下

app.config(function ($locationProvider){ 
    $locationProvider.html5Mode({ 
     enabled: true, 
     requireBase: false 
    }); 
}); 

入住這plunker

0

如果您正在使用angularJS 1 *(我不知道這是否是同樣的方式與angular2),你可以使用$ routeProvider然後$ routeParams從您的網址,以獲取價值

檢查這個網站有一個良好爲例:http://heycodetech.com/how-to-get-the-url-parameters-using-angularjs/

如果要使用該服務$位置,你的問題米這是因爲你沒有綁定「用戶」。嘗試類似的東西:

https://url.com/index.html?user='toto' 

.controller(‘myController’, function ($scope,$location) { 
$outputJson = $location.search(); // will get all parameter of your URL in json format 
var param1 = $location.search().user; // will get the value bond to "user" 
});