English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

AngularJS 지시의 상호작용 자세히 설명 및 예제 코드

  배경 소개

  이 예제는 비디오의 예제로,动感超人이 있으며 세 가지 능력이 있습니다. 그것은 힘(strength), 속도(speed), 빛(light)입니다.

  이 세 가지 능력은 세 가지 속성으로 정의되어 있으며,动感超人을 태그로 정의하면 해당 속성을 추가하여 이 능력을 가질 수 있습니다.

  결과를 효과적으로 표시하기 위해 태그에 마우스의 응답 이벤트를 추가했습니다. 마우스가 해당 태그에 위치하면 메서드가 트리거되어 해당 능력을 출력합니다.

  프로그램 분석
  html 부분의 코드는 다음과 같습니다:       

 <div>
      <superman>nothing!</superman>
      <superman strength >strength!</superman>
      <superman strength speed >strength speed!</superman>
      <superman strength speed light >strength speed light!</superman>
    </div>

  그럼 어떻게 구현할까요? 먼저 모듈을 생성합니다:

var myAppModule = angular.module("myApp",[]);

  이 모듈의 기반 위에서 superman라는 태그를 생성합니다. 이는 이전과 유사합니다.

myAppModule.directive("superman",function(){
        return{
          scope:{},
          restrict:'AE',
          transclude:true,
          template:"<div><div ng-transclude></div></div>"
          controller:function($scope){
            $scope.abilities = [];
            this.addStrength = function(){
              $scope.abilities.push("strength");
            };
            this.addSpeed = function(){
              $scope.abilities.push("speed");
            };
            this.addLight = function(){
              $scope.abilities.push("light");
            };
          },
          link:function(scope,element,attr){
            element.bind("mouseenter",function(){
              console.log(scope.abilities);
            });
          }
        }
      });

  이곳에서 다른 점은 메서드 내부에 controller 속성이 있으며, 이는 ng가 아닙니다.-controller와 같은 제어기 대신, 명령어가 공개적으로 제공하는 인터페이스는 외부에서 공개적으로 사용할 수 있는 메서드를 선언하고 있으며, 다른 명령어는 의존성을 통해 이 메서드를 사용할 수 있습니다.

  그래서 다음으로 세 가지 능력에对应的 명령어를 생성합니다.

    myAppModule.directive("strength",function(){
        return{
          require:'^superman',
          link:function(scope,element,attr,supermanCtrl){
            supermanCtrl.addStrength();
          }
        }
      });
      myAppModule.directive("speed",function(){
        return{
          require:'^superman',
          link:function(scope,element,attr,supermanCtrl){
            supermanCtrl.addSpeed();
          }
        }
      });
      myAppModule.directive("light",function(){
        return{
          require:'^superman',
          link:function(scope,element,attr,supermanCtrl){
            supermanCtrl.addLight();
          }
        }
      });

  세 가지 명령어의 코드는 모두 비슷하지만, require는 의존 명령어를 지정합니다.

  link에 supermanCtrl이라는 추가적인 매개변수가 있으며, 이 매개변수는 superman의 controller라는 의심이 있어 superman으로 이름을 붙였습니다.+Ctrl 방식으로。

  【由于不懂内部原理,这里仅仅是猜测,但是实验证明,如果改变这个参数的名字,会报错。】

  이 세 가지 지시를 선언하면 이 세 가지 지시를 super의 속성으로 사용할 수 있습니다. 해당 속성을 지정하면 내부의 link에서의 메서드가 트리거되고 superman에서 공개된 메서드가 호출됩니다。  

  지시의 상호작용 과정을 요약하면 다음과 같습니다:

  1 먼저 기본 지시를 생성합니다. controller 속성 뒤에 공개된 메서드를 추가합니다;

  2 다른 상호작용 지시를 생성하려면,require 속성 뒤에 해당 지시 의존성을 추가하고,link에서 공개된 메서드를 호출합니다;

  전체 프로그램 코드:

!doctype html
<html ng-app="myApp">
  <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
  </head>
  <body>
    <div>
      <superman>nothing!</superman>
      <superman strength >strength!</superman>
      <superman strength speed >strength speed!</superman>
      <superman strength speed light >strength speed light!</superman>
    </div>
    <script type="text/javascript">
      var myAppModule = angular.module("myApp",[]);
      myAppModule.directive("superman",function(){
        return{
          scope:{},
          restrict:'AE',
          transclude:true,
          template:"<div><div ng-transclude></div></div>"
          controller:function($scope){
            $scope.abilities = [];
            this.addStrength = function(){
              $scope.abilities.push("strength");
            };
            this.addSpeed = function(){
              $scope.abilities.push("speed");
            };
            this.addLight = function(){
              $scope.abilities.push("light");
            };
          },
          link:function(scope,element,attr){
            element.bind("mouseenter",function(){
              console.log(scope.abilities);
            });
          }
        }
      });
      myAppModule.directive("strength",function(){
        return{
          require:'^superman',
          link:function(scope,element,attr,supermanCtrl){
            supermanCtrl.addStrength();
          }
        }
      });
      myAppModule.directive("speed",function(){
        return{
          require:'^superman',
          link:function(scope,element,attr,supermanCtrl){
            supermanCtrl.addSpeed();
          }
        }
      });
      myAppModule.directive("light",function(){
        return{
          require:'^superman',
          link:function(scope,element,attr,supermanCtrl){
            supermanCtrl.addLight();
          }
        }
      });
    </script>
  </body>
</html>

 실행 결과:

        위는 AngularJS 지시의 상호작용 자료 정리입니다. 향후 추가적인 자료를 보충할 예정입니다. 감사합니다.

성명: 이 문서의 내용은 인터넷에서 가져왔으며, 저작권은原作者에게 있으며, 인터넷 사용자가 자발적으로 기여하고 자체적으로 업로드한 것이며, 이 사이트는 소유권을 가지지 않으며, 인공적으로 편집되지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 문제가 의심되는 내용이 있다면, notice#w로 이메일을 보내 주세요.3codebox.com(보고서를 작성할 때는 #을 @으로 변경하십시오. 기타 증거를 제공하고, 실제로 확인되면 이 사이트는 즉시 의심스러운 저작권 내용을 제거합니다.

당신이 좋아할 만한 것