source

디렉티브의 method 인수가 AngularJS에 지정되어 있는지 확인하는 방법

nicesource 2023. 3. 5. 09:55
반응형

디렉티브의 method 인수가 AngularJS에 지정되어 있는지 확인하는 방법

버튼이 포함된 커스텀 디렉티브를 작성했습니다.이 버튼은 '콜백' 속성으로 지정된 부모 범위에서 메서드를 호출합니다.

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title>Simple directive</title>

    <script src="js/lib/angular/angular.js"></script>

    <script type="text/javascript">
        var app = angular.module('app', []);

        app.controller('TestController', function($scope) {

            $scope.doSomething = function(param) {
                alert('Something called with: ' + param);
            }
        })

        app.directive('myDirective', function() {
            var ret = {
                restrict: 'E',
                scope: {
                    user: '@',
                    callback: '&'       // bound a function from the scope
                },
                template: '<div>Hello {{user}}<button ng-show="hasCallback()" ng-click="callback({userData: user})">Callback</button>',
                controller: function($scope) {
                    $scope.hasCallback2 = function() {
                        var t = typeof $scope.callback;
                        return t == 'function';
                    }

                    $scope.hasCallback = function() {
                        return angular.isDefined($scope.callback);
                    }
                }
            };
            return ret;
        });

    </script>
</head>

<body ng-controller="TestController">

<my-directive user="cat" callback="doSomething(userData)"></my-directive>
<my-directive user="dog" callback="doSomething(userData)"></my-directive>
<my-directive user="pig"></my-directive>

</body>

</html>

질문입니다.

템플릿 내부의 버튼 표시 여부를 제어하려면 어떻게 해야 합니까?커스텀 태그에 callback 속성이 지정되어 있지 않은 경우는 숨기고 싶다(3rd my-directive 태그 참조).콜백 유형을 체크하면 항상 function이 표시되며 angular.isDefined(...)도 true를 반환합니다.

&?를 사용하면 속성이 설정되지 않은 경우 정의되지 않은 상태로 반환됩니다.

'&' = 콜백 함수는 항상 정의됩니다.

&? = callback 함수는 속성이 html 템플릿에 정의되어 있는 경우에만 정의됩니다.

bindToController: {
    callback: '&?'
},
controller: function() {
    if (this.callback === undefined) {
        // attribute "callback" was not defined
    }
}

주의: Angular 1.4.8로 동작합니다.이전 버전에서도 작동되는지 잘 모르겠어요.

angularjs 소스 코드를 보면 다음과 같습니다.

case '&':
    parentGet = $parse(attrs[attrName]);
    isolateScope[scopeName] = function(locals) {
         return parentGet(scope, locals);
    };
    break;

parentGet는 바운드 함수식입니다.안타깝게도 이것은 로컬 변수이며, 이는 에 할당된 함수에서만 사용할 수 있습니다.isolateScope[scopeName]폐쇄를 통해.

이 변수를 얻는 방법을 찾는 대신 간단한 해결책은 이 변수를 체크하는 것입니다.attrs. 시험해 보세요.

link: function(scope,elem,attrs) {

      scope.hasCallback = function() {
        return angular.isDefined(attrs.callback);
      }
    }

데모

언급URL : https://stackoverflow.com/questions/21935099/how-to-check-if-a-method-argument-of-a-directive-is-specified-in-angularjs

반응형