Angular - 动态href - <a> vs controller $window.location.href

时间:2016-08-17 00:49:20

标签: javascript angularjs

So I have a simple page where the user types in an ID in an input and hits the "Go" button. I was using an onSubmit function and it was working fine. Then I changed some Angular code to include html5 enabled to remove the /#/ from urls.

search.template.html

<div class="row">
    <div class="small-12 column header-title">
        <h2>{{ svm.title }}</h2><h5>BETA</h5>
    </div>
</div>

<form role="form" ng-submit="svm.onSubmit()">
<div class="row">

    <div class="small-12 small-centered columns">

        <div class="row collapse postfix-round">

            <div class="small-9 columns">
                <input ng-model="svm.formData.eventid" class="event-id" type="text" placeholder="Event ID" maxlength="7">
            </div>
            <div class="small-3 columns">
                <button type="submit" class="button postfix event-submit">Go</button>
            </div>
            <div role="alert" ng-show="svm.formData.formError" class="alert alert-danger event-id-error">{{ svm.formData.formError }}</div>

        </div>

    </div>

</div>
</form>

search.controller.js

(function() {

    angular
    .module('monitorApp')
    .controller('searchCtrl', searchCtrl);

    searchCtrl.$inject = ['$window'];
    function searchCtrl($window) {
        var vm = this;
        vm.title = 'Monitor';

        vm.formData = {};
        vm.onSubmit = function() {
            vm.formError = '';
            if (!vm.formData.eventid) {
                vm.formData.formError = 'Please enter Event ID.';
                return false;
            } else {
                vm.formData.formError = '';
                $window.location.href = '/#event/' + vm.formData.eventid;
                return false;
            }
        };
    }

})();

So you may see in the controller $window.location.href = '/event/' + vm.formData.eventid; that I use to use to submit the event. Now since the `html5Mode(true) addition, it seems to not only be broken, but if it worked, it sends me to the server side routing, which is not right. It should be using Angular routing.

So I'm here trying to find how to not only fix it, but how should this be done properly to utilize Angular routing (and not server side routing). Thanks for any help!

1 个答案:

答案 0 :(得分:2)

改为使用$location服务:

function searchCtrl($location) {
    var vm = this;
    vm.title = 'Monitor';

    vm.formData = {};
    vm.onSubmit = function() {
        vm.formError = '';
        if (!vm.formData.eventid) {
            vm.formData.formError = 'Please enter Event ID.';
            return false;
        } else {
            vm.formData.formError = '';
            $location.path('/event/' + vm.formData.eventid);
            return false;
        }
    };
}