IT박스

Angular.js 속성 지시문에 여러 속성을 어떻게 전달합니까?

itboxs 2020. 7. 23. 19:42
반응형

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()
        }
    };
});

fiddle

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();
});

참고URL : https://stackoverflow.com/questions/16546771/how-do-i-pass-multiple-attributes-into-an-angular-js-attribute-directive

반응형