[angularjs] ng-click을 사용하여 경로를 호출하는 방법 / 언제?

경로를 사용한다고 가정하십시오.

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

그리고 HTML에서 버튼을 클릭하면 정보 페이지로 이동하려고합니다. 한 가지 방법은

<a href="#/about">

…하지만 ng-click이 여기에서도 유용 할 것 같습니다.

  1. 그 가정이 맞습니까? 앵커 대신 ng-click을 사용 하시겠습니까?
  2. 그렇다면 어떻게 작동합니까? IE :

<div ng-click="/about">



답변

경로는 $location서비스를 모니터링하고 URL의 변경 사항 (일반적으로 해시를 통해)에 응답합니다. 경로를 “활성화”하려면 간단히 URL을 변경하면됩니다. 가장 쉬운 방법은 앵커 태그를 사용하는 것입니다.

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

더 복잡한 것은 필요하지 않습니다. 그러나 코드에서이 작업을 수행해야하는 경우 $location서비스 를 사용하는 것이 좋습니다 .

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

예를 들어, 버튼으로 다음을 트리거 할 수 있습니다.

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


답변

아무도 언급하지 않은 훌륭한 팁이 있습니다. 함수가있는 컨트롤러에서 위치 제공자를 포함해야합니다.

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>


답변

지시문으로 구현 된 사용자 정의 속성을 사용하는 것이 가장 깨끗한 방법 일 것입니다. @Josh와 @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);
                });
            });
        }
    }
}]);

유용한 기능이 있지만 Angular를 처음 사용하므로 개선의 여지가 있습니다.


답변

라우팅에 ng-click을 사용하면 요소를 마우스 오른쪽 버튼으로 클릭하고 ‘새 탭에서 열기’를 선택하거나 링크를 클릭하여 ctrl을 선택할 수 없습니다. 탐색 할 때 ng-href를 사용하려고합니다. ng-click은 축소 또는 축소와 같은 시각 효과 나 조작에 단추를 사용하는 것이 좋습니다. 그러나 나는 추천하지 않습니다. 경로를 변경하면 응용 프로그램에 배치 된 경로를 많이 변경해야 할 수도 있습니다. 링크를 돌려주는 메소드가 있습니다. 예 : 정보. 유틸리티에 배치하는이 방법


답변

내가 사용 ng-click하는 결정, 경로 templateUrl를 요청하면서, 함수를 호출하는 지시어 <div>수있다 show또는 hide내부 경로 templateUrl 페이지 또는 다른 시나리오를.

AngularJS 1.6.9

라우팅 페이지 에서 부모 컨트롤러 모델 과 부울을 사용하여 제어 하는 add <div>또는 edit 가 필요합니다 .<div>$scope.addProduct$scope.editProduct

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>

두 페이지-
RoutingTesting.html(부모), TestingPage.html(라우팅 페이지)가 같은 디렉토리에 있습니다.

이것이 누군가를 도울 수 있기를 바랍니다.


답변

ng-click을 사용하지 않는 다른 솔루션이지만 다음과 같은 다른 태그에서도 여전히 작동합니다 <a>.

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

이 방법으로 경로에 매개 변수를 전달할 수도 있습니다 : https://stackoverflow.com/a/40045556/838494

(이것은 각도가있는 첫날입니다. 부드러운 피드백을 환영합니다)


답변

당신이 사용할 수있는:

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

href 내부에 동적 변수를 원하면 다음과 같이 할 수 있습니다.

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

여기서 링크 는 각도 범위 변수입니다.