使用ng模型更改AngularJS URL



有什么方法可以用ng模型更改AngularJS URL吗?

var scotchApp = angular.module('scotchApp', ['ngRoute']);
scotchApp.controller('mainController', function($scope) {
    $scope.gettext = function (){
          
    };
});
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="scotchApp">
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
        <script src="eventChange.js"></script>
    </head>
    <body ng-controller="mainController">
        <div class="container">
            <div class="row">
                <div class="col-sm-1">Search</div>
                <div class="col-sm-3"><input type="text" class="form-control" ng-model="search" ng-change="gettext()"></div>
            </div>
        </div>          
    </body>
</html>

我需要把URL改成这样http://localhost/angulRoute/search=myVal当用户在搜索框中键入"myVal"时(实际上在具有搜索值的gettext()函数内)

您可以在控制器中执行以下操作:

$scope.query = $location.search().q;
$scope.$watch('query', function(newValue) {
    $location.search('q', newValue);
});

您需要将$location注入控制器,并确保在您的路由配置中包括:

reloadOnSearch: true

这将导致一个URLhttp://localhost/myRoute?q=myVal

注意:我还将ng model options="{updateOn:'blu'}"添加到您的输入中,以防止每次按键都更新URL。

示例

以下是如何做到这一点的工作示例:http://plnkr.co/edit/tphqPeJ0dO74Ux7WpXlU?p=preview

请注意,由于plnkr.co的工作方式,您不会在该网站的地址栏中看到URL的更改。如果您下载代码并在本地运行,URL将在地址栏中更新。

嗨,我找到了一个javascript解决方案。

 $scope.gettext = function (search){
    window.history.pushState("object or string", "Title", "/angulRoute/search="+search);
};

使用<input type="text" class="form-control" ng-model="search" ng-change="gettext(search)" >对我有效。然而,任何人都有AngulerJs解决方案,欢迎他们:D

最新更新