티스토리 뷰
■ 지시자 독립 scope 정의방법
1. scope {name : "@to" }
to는 부모 scope의 속성명이 아니라 연결된 DOM의 속성명 - 3가지 방식에서 의미 동일함
scope {name : "@" } //"@"만 사용하게 되면 DOM 속성의 이름과 scope 내부 속성의 이름이 같다고 판단
<!DOCTYPE html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script type="text/javascript">
angular.module('sampleApp', [])
.controller('demoCtrl', ['$scope', function($scope){
$scope.name="Ctrl에서 사용된 name 모델";
}])
.directive('hello', function(){
return {
template: '<h1>hello <span>{{name}}</span></h1>',
restrict:"AE",
scope:{name:"@to"}
}
});
</script>
</head>
<body ng-controller="demoCtrl">
<div hello to="google"></div>
<div hello to="naver"></div>
<div hello></div>
</body>
</html>
2. scope: {send : "&"}
scope 설정에서 속성의 값으로 "&"나 "&연결된 DOM 속성명"을 주면 부모 scope의 환경에서 실행될 수 있는 표현식에 대한 레퍼런스(reference)를 가지고 올 수 있다
<!DOCTYPE html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script type="text/javascript">
angular.module('sampleApp', [])
.controller('demoCtrl', ['$scope', function($scope){
$scope.helloList=[{name:'google'}, {name:'naver'}, {name:'angular'}];
$scope.sendMessage = function(toSb){
console.log(toSb+"에게 메시지를 보낸다.");
};
}])
.directive('hello', function(){
return{
template: '<h1>hello <span>{{name}}</span><button ng-click="send()">메시지 보내기</button></h1>',
restrict : "AE",
scope : {
name:"@to",
send:"&"
}
}
});
</script>
</head>
<body ng-controller="demoCtrl">
<div ng-repeat="helloSb in helloList" hello to="{{helloSb.name}}" send="sendMessage(helloSb.name)">
</div>
</body>
</html>
3. scope: {name : "=to"}
<!DOCTYPE html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script type="text/javascript">
angular.module('sampleApp', [])
.controller('demoCtrl',['$scope', function($scope){
$scope.helloList = [{name: 'google'}, {name: 'naver'}, {name: 'angular'}];
}])
.directive('hello', function(){
return{
template : '<h1>hello <span>{{name}}</span><input type="text" ng-model="name"></h1>',
restrict : "EA",
scope: {
name : "=to"
}
}
});
</script>
</head>
<body ng-controller="demoCtrl">
<ul>
<li ng-repeat="helloSb in helloList">
<input type="text" ng-model="helloSb.name">
</li>
</ul>
<div ng-repeat="helloSb in helloList" hello to="helloSb.name"></div>
</body>
</html>
출처: http://kshmc.tistory.com/entry/18-지시자-2-사용자-정의-지시자
'Javascript > 일반' 카테고리의 다른 글
[webpack] webpack 버전4에서 Optional chaining 사용하기 (0) | 2022.08.11 |
---|---|
js Promise (0) | 2019.07.30 |