반응형
디렉티브의 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
반응형
'source' 카테고리의 다른 글
IE의 jQuery 스크립트에 대한 액세스가 거부되었습니다. (0) | 2023.03.05 |
---|---|
HTML5 비디오에서 오른쪽 클릭을 비활성화하시겠습니까? (0) | 2023.03.05 |
비활성 JSON 문자열을 자동으로 수정하려면 어떻게 해야 합니까? (0) | 2023.03.05 |
상위 구성 요소의 하위 구성 요소 참조에 액세스하는 방법 (0) | 2023.03.05 |
jQuery의 .ajax() 메서드가 세션쿠키를 송신하지 않는 이유는 무엇입니까? (0) | 2023.03.05 |