How/when to use ng-click to call a route?

2019-01-08 03:11发布

Suppose you are using routes:

// bootstrap
myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

    $routeProvider.when('/home', {
        templateUrl: 'partials/home.html',
        controller: 'HomeCtrl'
    });
    $routeProvider.when('/about', {
        templateUrl: 'partials/about.html',
        controller: 'AboutCtrl'
    });
...

And in your html, you want to navigate to the about page when a button is clicked. One way would be

<a href="#/about">

... but it seems ng-click would be useful here too.

  1. Is that assumption correct? That ng-click be used instead of anchor?
  2. If so, how would that work? IE:

<div ng-click="/about">

8条回答
forever°为你锁心
2楼-- · 2019-01-08 03:40

Here's a great tip that nobody mentioned. In the controller that the function is within, you need to include the location provider:

app.controller('SlideController', ['$scope', '$location',function($scope, $location){ 
$scope.goNext = function (hash) { 
$location.path(hash);
 }

;]);

 <!--the code to call it from within the partial:---> <div ng-click='goNext("/page2")'>next page</div>
查看更多
干净又极端
3楼-- · 2019-01-08 03:45

Using a custom attribute (implemented with a directive) is perhaps the cleanest way. Here's my version, based on @Josh and @sean's suggestions.

angular.module('mymodule', [])

// Click to navigate
// similar to <a href="#/partial"> but hash is not required, 
// e.g. <div click-link="/partial">
.directive('clickLink', ['$location', function($location) {
    return {
        link: function(scope, element, attrs) {
            element.on('click', function() {
                scope.$apply(function() {
                    $location.path(attrs.clickLink);
                });
            });
        }
    }
}]);

It has some useful features, but I'm new to Angular so there's probably room for improvement.

查看更多
登录 后发表回答