如何在URL中传递角度JS值作为参数

时间:2017-04-13 11:35:21

标签: angularjs arrays

我有以下链接

<a href="entity-details.html?id='{{ x.community_id }}&community_society_id={{x.community_society_id}}">View</a>

我希望x.community_id和x.community_society_id值传递给控制器​​,然后我会获取数据。

var app = angular.module('EntityApp', []);
app.controller('EntityAppCntroller', function($scope, $http, $location) {   
    var myParamtr = location.search.split('id=')[1] ? location.search.split('id=')[1] : 'myDefaultValue';   
    alert(myParamtr);
    $http.get('apartment/community/details/list/'+ myParam).then(function(response) {
        $scope.myData = response.data.list;
    });
});

1 个答案:

答案 0 :(得分:0)

您需要使用ng-href,以便可以将值构建到链接中。 Lke @tanmay在评论中说。

<a ng-href="entity-details.html?id={{ x.community_id }}&community_society_id={{x.community_society_id}}">View</a>

更改控制器以正确解析网址。

var app = angular.module('EntityApp', []);
app.controller('EntityAppCntroller', function($scope, $http, $location) {   

     var getJsonFromUrl = function(url) {
        console.log(url);
        var query = url.substr(1);
        var result = {};
        query.split("&").forEach(function(part) {
          var item = part.split("=");
          result[item[0]] = decodeURIComponent(item[1]);
        });
        return result;
     };

    var queryParams = getJsonFromUrl(location.search);

    var myParamtr = queryParams.id ? queryParams.id : 'myDefaultValue';   

    alert(myParamtr);

    $http.get('apartment/community/details/list/'+ myParam).then(function(response) {
        $scope.myData = response.data.list;
    });

});