반응형
요소에 속성을 추가하는 각도 지시문?
이 단편은 어떻게 작업해야 하는지 궁금해요.
//html
<div ng-app="app">
<div ng-controller="AppCtrl">
<a my-dir ng-repeat="user in users">{{user.name}}</a>
</div>
</div>
//js
var app = angular.module('app', []);
app.controller("AppCtrl", function ($scope) {
$scope.users = [{name:'John',id:1},{name:'anonymous'}];
$scope.fxn = function() {
alert('It works');
};
})
app.directive("myDir", function ($compile) {
return {
link:function(scope,el){
el.attr('ng-click','fxn()');
//$compile(el)(scope); with this the script go mad
}
};
});
컴파일 단계인 건 알지만 요점을 잘 모르겠으니 간단한 설명을 해주시면 감사하겠습니다.
같은 요소에 다른 디렉티브를 추가하는 디렉티브:
유사한 답변:
여기 plunker가 있습니다.http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview
app.directive("myDir", function($compile) {
return {
priority:1001, // compiles first
terminal:true, // prevent lower priority directives to compile after it
compile: function(el) {
el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
el.attr('ng-click', 'fxn()');
var fn = $compile(el);
return function(scope){
fn(scope);
};
}
};
});
훨씬 깨끗한 솔루션 - 사용하지 않음ngClick
전혀:
plunker : http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview
app.directive("myDir", function($parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('fxn()');
return function (scope,elm){
elm.bind('click',function(){
exp(scope);
});
};
}
};
});
다음과 같이 시험해 보십시오.
<div ng-app="app">
<div ng-controller="AppCtrl">
<a my-dir ng-repeat="user in users" ng-click="fxn()">{{user.name}}</a>
</div>
</div>
<script>
var app = angular.module('app', []);
function AppCtrl($scope) {
$scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
$scope.fxn = function () {
alert('It works');
};
}
app.directive("myDir", function ($compile) {
return {
scope: {ngClick: '='}
};
});
</script>
언급URL : https://stackoverflow.com/questions/21687925/angular-directive-how-to-add-an-attribute-to-the-element
반응형
'sourcecode' 카테고리의 다른 글
react.js & redux에서 componentDisMount가 여러 번 호출된 이유는 무엇입니까? (0) | 2023.04.03 |
---|---|
주석 지정 콩 이름이 호환되지 않는 기존 콩 이름과 충돌합니다. (0) | 2023.03.29 |
JSON 개체를 jq의 key=value 형식으로 변환하는 방법은 무엇입니까? (0) | 2023.03.29 |
Redx를 사용한 리액트 라우터 변경에 대응하여 새 데이터를 가져오는 방법 (0) | 2023.03.29 |
화면에 [Object Object]가 아닌 JSON 표현을 표시하는 방법 (0) | 2023.03.29 |