angularjs - refresh when clicked on link with actual url

后端 未结 10 1248
深忆病人
深忆病人 2020-12-02 10:13

I use routeProvider to define controlers and templates for my urls.

When I click on the link, which has the same url as is the actual location, nothing happens. I w

相关标签:
10条回答
  • 2020-12-02 10:35

    Add a / (slash) to the defined url in the route configuration

    I met a similar problem today, I have a link in my web page and when I click it, I want the ng-view reload each time, so that I can refresh data from server. But if the url location doesn't change, angular doesn't reload the ng-view.

    Finally, i found a solution to this problem. In my web page, I set the link href to:

    • <a href="#/test">test</a>

    But in the route config, I set:

    • $routeProvider.when('/test/', { controller: MyController, templateUrl:'/static/test.html' });

    The different is the last slash in url. When I click href="#/test" for the first time, angular redirect the url to #/test/, and load ng-view. when i click it second time, because the current url is #/test/, it's not equal to the url in the link (href="#/test") I clicked, so Angular triggers the location change method and reloads the ng-view, in addition Angular redirects the url to #/test/ again. next time i click the url, angular does the same thing again. Which is exactly what I wanted.

    Hope this was useful for you.

    0 讨论(0)
  • 2020-12-02 10:35

    I think it's a simpler approach.

    .directive ('a', function ($route, $location) {
        var d = {};
        d.restrict = 'E';
        d.link = function (scope, elem, attrs) {
    
            // has target
            if ('target' in attrs) return;
    
            // doesn't have href
            if (!('href' in attrs)) return;
    
            // href is not the current path
            var href = elem [0].href;
            elem.bind ('click', function () {
                if (href !== $location.absUrl ()) return;
                $route.reload ();
            });
        };
        return d;
    });
    

    Assuming You want to make all basic <a> links (without target attribute) reload on click and You use relative links in the href attribute (e.g. /home instead of http://example.com/home) You don't have to add any special markup to your HTML (comes handy when updating a site with HTML already written).

    0 讨论(0)
  • 2020-12-02 10:41

    For people who are using AngularUI Router. You can use something like this:

    <a data-ui-sref="some.state" data-ui-sref-opts="{reload: true}">State</a>
    

    Notice the reload option.

    Found the answer here: https://stackoverflow.com/a/29384813/426840

    0 讨论(0)
  • 2020-12-02 10:42

    you should use $route.reload() to force the reload.

    I don't know if is there a 'automatic' way to do this, but you can use ng-click on these links

    0 讨论(0)
提交回复
热议问题