Programing

href는 Angular.js에서 ng-click을 재정의합니다.

crosscheck 2020. 7. 26. 12:25
반응형

href는 Angular.js에서 ng-click을 재정의합니다.


href 및 ng-click 속성이 모두 정의 된 경우 :

<a href="#" ng-click="logout()">Sign out</a>

href속성은 ng를 클릭보다 우선합니다.

ng-click의 우선 순위를 높이는 방법을 찾고 있습니다.

href Twitter Bootstrap에 필요합니다. 제거 할 수 없습니다.


URI가 필요없는 경우 버튼 태그를 사용해야합니다.


각도 문서 사이트 의이 예제 href는 빈 문자열에 할당 하지 않아도됩니다.

[<a href ng-click="colors.splice($index, 1)">X</a>]

http://docs.angularjs.org/api/ng.directive:select


템플릿에서 직접 클릭 이벤트의 기본 동작을 방지 할 수 있습니다.

<a href="#" ng-click="$event.preventDefault();logout()" />

각 문서 ,

ngClick 및 ngFocus와 같은 지시문은 해당 표현식의 범위 내에서 $ event 객체를 노출합니다.


또 다른 해결책은 다음과 같습니다.

<a href="" ng-click="logout()">Sign out</a>

즉, href 속성에서 #을 제거하십시오.


힌트 하나만 더 브라우저 접근성을 지원하기 위해 실제 URL이 필요한 경우 다음을 수행 할 수 있습니다.

주형:

<a ng-href="{{link}}" ng-click="$event.preventDefault(); linkClicked(link)">{{link}}</a>

지령:

$scope.linkClicked = function(link){
    // your code here
    $location.path(link);
};

이런 식으로 linkClicked ()의 코드는 링크로 이동하기 전에 실행될 기회를 갖습니다


Angular에서 <a>s는 지시문 입니다. 따라서 비어 href있거나없는 href경우 Angular는을 호출 event.preventDefault합니다.

로부터 소스 :

    element.on('click', function(event){
      // if we have no href url, then don't navigate anywhere.
      if (!element.attr(href)) {
        event.preventDefault();
      }
    });

다음 은 누락 된 시나리오를 보여주는 plnkrhref 입니다.


이것은 IE 9 및 AngularJS v1.0.7에서 저에게 효과적이었습니다.

<a href="javascript:void(0)" ng-click="logout()">Logout</a>

작업 솔루션에 대한 duckeggs의 의견감사드립니다 !


여기 에이 질문에 대한 많은 답변이 있지만 실제로 여기서 일어나는 일에 대해 약간의 혼란이있는 것 같습니다.

첫째, 당신의 전제

"href는 Angular.js의 ng-click보다 우선합니다"

잘못되었습니다. 실제로 발생하는 것은 클릭 후 click 이벤트가 먼저 angular ( ng-clickangular 1.x 및 clickangular 2.x +의 지시문에 의해 정의 됨)에 의해 처리 된 다음 계속 전파됩니다 (결국 브라우저를 통해 href속성으로 정의 된 URL ). ( 자바 스크립트의 이벤트 전파에 대한 자세한 내용은 항목 참조 )

이를 피하려면 Event 인터페이스의 preventDefault()메소드를 사용하여 이벤트 전파를 취소해야합니다 .

<a href="#" ng-click="$event.preventDefault();logout()" />

(이것은 순수한 자바 스크립트 기능이며 각도와 관련이 없습니다)

Now, this will already solve your problem but this is not the optimal solution. Angular, rightfully, promotes the MVC pattern. With this solution, your html template is mixed with the javascript logic. You should try to avoid this as much as possible and put your logic into your angular controller. So a better way would be

<a href="#" ng-click="logout($event)" />

And in your logout() method:

logout($event) {
   $event.preventDefault();
   ...
}

Now the click event will not reach the browser, so it will not try to load the link pointed by href. (However note that if the user right clicks on the link and directly opens the link, then there won't be a click event at all. Instead it will directly load the url pointed by the href attribute.)

Regarding the comments about visited link color in the browsers. Again this has nothing to do with angular, if your href="..." points to a visited url by your browser by default the link color will be different. This is controlled by CSS :visited Selector, you can modify your css to override this behaviour:

a {
   color:pink;
}

PS1:

Some answers suggest to use:

<a href .../>

href is an angular directive. When your template is processed by angular this will be converted to

<a href="" .../>

Those two ways are essentially the same.


Just write ng-click before href ..It worked for me

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
    <script>
    angular.module("module",[])
.controller("controller",function($scope){
  
  $scope.func =function(){
    console.log("d");
  }
  
})</script>
  </head>

  <body ng-app="module" ng-controller="controller">
    <h1>Hello ..</h1>
    <a ng-click="func()" href="someplace.html">Take me there</a>
  </body>

</html>


I don't think you need to remove "#" from href. Following works with Angularjs 1.2.10

<a href="#/" ng-click="logout()">Logout</a>

You can also try this:

<div ng-init="myVar = 'www.thesoftdesign'">
        <h1>Tutorials</h1>
        <p>Go to <a ng-href="{{myVar}}">{{myVar}}</a> to learn!</p>
</div>

I'll add for you an example that work for me and you can change it as you want.

I add the bellow code inside my controller.

     $scope.showNumberFct = function(){
        alert("Work!!!!");
     }

and for my view page I add the bellow code.

<a  href="" ng-model="showNumber" ng-click="showNumberFct()" ng-init="showNumber = false" >Click Me!!!</a>

Did you try redirecting inside the logout function itself? For example, say your logout function is as follows

$scope.logout = function()
{
  $scope.userSession = undefined;
  window.location = "http://www.yoursite.com/#"
}

Then you can just have

<a ng-click="logout()">Sign out</a>

Please check this

<a href="#" ng-click="logout(event)">Logout</a>

 $scope.logout = function(event)


 {
event.preventDefault();
alert("working..");
}

//for dynamic elements - if you want it in ng-repeat do below code

angular.forEach($scope.data, function(value, key) {
     //add new value to object
    value.new_url  = "your url";
});

 <div ng-repeat="row in data"><a ng-href="{{ row.url_content }}"></a></div>

This works for me

<a href (click)="logout()">
   <i class="icon-power-off"></i>
   Logout
</a>

참고URL : https://stackoverflow.com/questions/14939385/href-overrides-ng-click-in-angular-js

반응형