Angular.js 속성 지시문에 여러 속성을 어떻게 전달합니까?
다음과 같이 속성 지시문이 제한되었습니다.
restrict: "A"
두 가지 속성을 전달해야합니다. attrs
객체를 사용하여 지시문 내에서 액세스하는 숫자와 함수 / 콜백 .
지시문이 요소 지시문 인 경우 다음으로 제한 "E"
할 수 있습니다.
<example-directive example-number="99" example-function="exampleCallback()">
그러나 들어 가지 않는 이유 때문에 속성 지시문이되기 위해서는 지시문이 필요합니다.
속성 지시문에 여러 속성을 전달하려면 어떻게합니까?
지시문 자체가 요소가 아니더라도 지시문은 동일한 요소에 정의 된 모든 속성에 액세스 할 수 있습니다.
주형:
<div example-directive example-number="99" example-function="exampleCallback()"></div>
지령:
app.directive('exampleDirective ', function () {
return {
restrict: 'A', // 'A' is the default, so you could remove this line
scope: {
callback : '&exampleFunction',
},
link: function (scope, element, attrs) {
var num = scope.$eval(attrs.exampleNumber);
console.log('number=',num);
scope.callback(); // calls exampleCallback()
}
};
});
attribute의 값이 example-number
하드 코딩 될 경우 $eval
한 번 사용 하고 값을 저장하는 것이 좋습니다 . 변수 num
는 올바른 유형 (숫자)을 갖습니다.
요소 지시문과 동일한 방식으로 수행합니다. attrs 객체에 포함시킬 것입니다. 내 샘플에는 분리 범위를 통한 양방향 바인딩이 있지만 필수는 아닙니다. 격리 된 범위를 사용하는 경우 scope.$eval(attrs.sample)
scope.sample을 사용 하거나 단순히 속성에 액세스 할 수 있지만 상황에 따라 연결시 정의되지 않을 수 있습니다.
app.directive('sample', function () {
return {
restrict: 'A',
scope: {
'sample' : '=',
'another' : '='
},
link: function (scope, element, attrs) {
console.log(attrs);
scope.$watch('sample', function (newVal) {
console.log('sample', newVal);
});
scope.$watch('another', function (newVal) {
console.log('another', newVal);
});
}
};
});
로 사용 :
<input type="text" ng-model="name" placeholder="Enter a name here">
<input type="text" ng-model="something" placeholder="Enter something here">
<div sample="name" another="something"></div>
객체를 속성으로 전달하여 다음과 같이 지시문으로 읽을 수 있습니다.
<div my-directive="{id:123,name:'teo',salary:1000,color:red}"></div>
app.directive('myDirective', function () {
return {
link: function (scope, element, attrs) {
//convert the attributes to object and get its properties
var attributes = scope.$eval(attrs.myDirective);
console.log('id:'+attributes.id);
console.log('id:'+attributes.name);
}
};
});
이것은 나를 위해 일했고 더 HTML5 호환이라고 생각합니다. 'data-'접두사를 사용하도록 HTML을 변경해야합니다
<div data-example-directive data-number="99"></div>
그리고 지시문 내에서 변수 값을 읽으십시오.
scope: {
number : "=",
....
},
다른 지시문에서 'exampleDirective'를 '필요'하면 논리가 'exampleDirective 's 컨트롤러에 있습니다 ('exampleCtrl '이라고 말함).
app.directive('exampleDirective', function () {
return {
restrict: 'A',
scope: false,
bindToController: {
myCallback: '&exampleFunction'
},
controller: 'exampleCtrl',
controllerAs: 'vm'
};
});
app.controller('exampleCtrl', function () {
var vm = this;
vm.myCallback();
});
'IT박스' 카테고리의 다른 글
iPad에서 만든 HTTP 요청을 어떻게 리디렉션합니까? (0) | 2020.07.23 |
---|---|
dom 렌더링이 완료된 후 지시문을 실행하려면 어떻게해야합니까? (0) | 2020.07.23 |
C #에서 상수 사전 만들기 (0) | 2020.07.23 |
쉘 스크립트에 도움말 메소드를 추가하려면 어떻게해야합니까? (0) | 2020.07.23 |
C 데이터 유형은“대부분의 컴퓨터에서 직접 지원”되는 방식은 무엇입니까? (0) | 2020.07.23 |