routeprovider route error change angularjs routes angularjs-routing angularjs-ng-click angularjs-ng-route

angularjs - route - ¿Cómo/cuándo usar ng-click para llamar una ruta?



angularjs routeparams (8)

Supongamos que está utilizando rutas:

// 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'' }); ...

Y en su html, desea navegar a la página acerca de cuando se hace clic en un botón. Una forma seria

<a href="#/about">

... pero parece que ng-click sería útil aquí también.

  1. ¿Es esa suposición correcta? Que ng-click sea usado en lugar de ancla?
  2. Si es así, ¿cómo funcionaría? ES DECIR:

<div ng-click="/about">


Aquí hay un gran consejo que nadie mencionó. En el controlador en el que se encuentra la función, debe incluir el proveedor de ubicación:

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>


Las rutas monitorean el servicio $location y responden a los cambios en la URL (generalmente a través del hash). Para "activar" una ruta, simplemente cambia la URL. La forma más fácil de hacerlo es con etiquetas de anclaje.

<a href="#/home">Go Home</a> <a href="#/about">Go to About</a>

No se necesita nada más complicado. Sin embargo, si debe hacer esto desde el código, la forma correcta es usar el servicio $location :

$scope.go = function ( path ) { $location.path( path ); };

Que, por ejemplo, un botón podría disparar:

<button ng-click="go(''/home'')"></button>


Otra solución, pero sin utilizar ng-click, que aún funciona incluso para otras etiquetas que <a> :

<a ng-href="#/about">About</a>

De esta manera también puede pasar parámetros a su ruta: https://.com/a/40045556/838494

(Este es mi primer día con angular. La retroalimentación gentil es bienvenida)


Puedes usar:

<a ng-href="{{link + 123}}">Link to 123</a>

Si quieres una variable dinámica dentro de href puedes hacerlo de esta manera:

<tr [routerLink]="[''/about'']">

Donde el enlace es variable de alcance angular.


Recuerde que si usa ng-click para enrutar, no podrá hacer clic derecho en el elemento y elegir "abrir en una nueva pestaña" o ctrl hacer clic en el enlace. Intento usar ng-href cuando se trata de la navegación. ng-click es mejor utilizar en botones para operaciones o efectos visuales como el colapso. Pero sobre no lo recomendaría. Si cambia la ruta, es posible que deba cambiar muchos de los colocados en la aplicación. Tener un método para devolver el enlace. ej: Acerca de. Este método lo colocas en una utilidad.


Usar un atributo personalizado (implementado con una directiva) es quizás la forma más limpia. Aquí está mi versión, basada en las sugerencias de @Josh y @sean.

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); }); }); } } }]);

Tiene algunas características útiles, pero soy nuevo en Angular, por lo que es probable que haya margen de mejora.


solo hazlo como sigue en tu html escribe:

<button ng-click="going()">goto</button>

Y en su controlador, agregue $ state como sigue:

.controller(''homeCTRL'', function($scope, **$state**) { $scope.going = function(){ $state.go(''your route''); } })


ng-click directiva ng-click para llamar a una función, mientras solicito routeUrl de ruta, para decidir qué <div> se debe show u hide dentro de la página de templateUrl de ruta o para diferentes escenarios.

AngularJS 1.6.9

Veamos un ejemplo, cuando en la página de enrutamiento, necesito el complemento <div> o la edición <div> , que controlo usando los modelos de controlador primario $scope.addProduct y $scope.editProduct boolean.

RoutingTesting.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Testing</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-route.min.js"></script> <script> var app = angular.module("MyApp", ["ngRoute"]); app.config(function($routeProvider){ $routeProvider .when("/TestingPage", { templateUrl: "TestingPage.html" }); }); app.controller("HomeController", function($scope, $location){ $scope.init = function(){ $scope.addProduct = false; $scope.editProduct = false; } $scope.productOperation = function(operationType, productId){ $scope.addProduct = false; $scope.editProduct = false; if(operationType === "add"){ $scope.addProduct = true; console.log("Add productOperation requested..."); }else if(operationType === "edit"){ $scope.editProduct = true; console.log("Edit productOperation requested : " + productId); } //*************** VERY IMPORTANT NOTE *************** //comment this $location.path("..."); line, when using <a> anchor tags, //only useful when <a> below given are commented, and using <input> controls $location.path("TestingPage"); }; }); </script> </head> <body ng-app="MyApp" ng-controller="HomeController"> <div ng-init="init()"> <!-- Either use <a>anchor tag or input type=button --> <!--<a href="#!TestingPage" ng-click="productOperation(''add'', -1)">Add Product</a>--> <!--<br><br>--> <!--<a href="#!TestingPage" ng-click="productOperation(''edit'', 10)">Edit Product</a>--> <input type="button" ng-click="productOperation(''add'', -1)" value="Add Product"/> <br><br> <input type="button" ng-click="productOperation(''edit'', 10)" value="Edit Product"/> <pre>addProduct : {{addProduct}}</pre> <pre>editProduct : {{editProduct}}</pre> <ng-view></ng-view> </div> </body> </html>

TestingPage.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .productOperation{ position:fixed; top: 50%; left: 50%; width:30em; height:18em; margin-left: -15em; /*set to a negative number 1/2 of your width*/ margin-top: -9em; /*set to a negative number 1/2 of your height*/ border: 1px solid #ccc; background: yellow; } </style> </head> <body> <div class="productOperation" > <div ng-show="addProduct"> <h2 >Add Product enabled</h2> </div> <div ng-show="editProduct"> <h2>Edit Product enabled</h2> </div> </div> </body> </html>

ambas páginas: RoutingTesting.html (padre), TestingPage.html (página de enrutamiento) están en el mismo directorio,

Espero que esto ayude a alguien.