AngularJS-ng-model을 사용하는 지시문 작성
지시문을 작성하는 요소와 동일한 ng-model을 사용하여 입력 필드를 작성하는 지시문을 작성하려고합니다.
지금까지 내가 생각해 낸 내용은 다음과 같습니다.
HTML
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
This scope value <input ng-model="name">
<my-directive ng-model="name"></my-directive>
</body>
</html>
자바 스크립트
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "Felipe";
});
app.directive('myDirective', function($compile) {
return {
restrict: 'E',
scope: {
ngModel: '='
},
template: '<div class="some"><label for="{{id}}">{{label}}</label>' +
'<input id="{{id}}" ng-model="value"></div>',
replace: true,
require: 'ngModel',
link: function($scope, elem, attr, ctrl) {
$scope.label = attr.ngModel;
$scope.id = attr.ngModel;
console.debug(attr.ngModel);
console.debug($scope.$parent.$eval(attr.ngModel));
var textField = $('input', elem).
attr('ng-model', attr.ngModel).
val($scope.$parent.$eval(attr.ngModel));
$compile(textField)($scope.$parent);
}
};
});
그러나 이것이이 시나리오를 처리하는 올바른 방법이라고 확신하지 못하며 ng-model 대상 필드의 값으로 제어가 초기화되지 않는 버그가 있습니다.
위 코드의 Plunker는 다음과 같습니다. http://plnkr.co/edit/IvrDbJ
이것을 처리하는 올바른 방법은 무엇입니까?
편집 : ng-model="value"
템플릿에서를 제거한 후 정상적으로 작동하는 것 같습니다. 그러나 이것이 올바른 방법인지 다시 확인하고 싶기 때문에이 질문을 열어 두겠습니다.
편집 :이 답변은 오래되어 오래된 것 같습니다. 그냥 머리 위로 올라가서 사람들을 타락시키지 않습니다. 더 이상 Angular를 사용하지 않으므로 개선하기에 좋은 위치에 있지 않습니다.
실제로 꽤 좋은 논리이지만 일을 약간 단순화 할 수 있습니다.
지령
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.model = { name: 'World' };
$scope.name = "Felipe";
});
app.directive('myDirective', function($compile) {
return {
restrict: 'AE', //attribute or element
scope: {
myDirectiveVar: '=',
//bindAttr: '='
},
template: '<div class="some">' +
'<input ng-model="myDirectiveVar"></div>',
replace: true,
//require: 'ngModel',
link: function($scope, elem, attr, ctrl) {
console.debug($scope);
//var textField = $('input', elem).attr('ng-model', 'myDirectiveVar');
// $compile(textField)($scope.$parent);
}
};
});
지시문이있는 HTML
<body ng-controller="MainCtrl">
This scope value <input ng-model="name">
<my-directive my-directive-var="name"></my-directive>
</body>
CSS
.some {
border: 1px solid #cacaca;
padding: 10px;
}
이 Plunker를 사용하여 실제로 볼 수 있습니다 .
다음은 내가 보는 것입니다.
- 'ng-model'을 사용하려는 이유를 이해하지만 귀하의 경우에는 필요하지 않습니다. ng-model은 기존 HTML 요소를 범위의 값과 연결 하는 것 입니다. 지시문을 직접 작성하기 때문에 'new'html 요소를 작성하므로 ng-model이 필요하지 않습니다.
편집 Mark가 자신의 의견에서 언급했듯이 ng-model을 사용할 수 없으며 컨벤션을 유지하기 위해 이유가 없습니다 .
- 지시문 ( '격리 된'범위)에 범위를 명시 적으로 지정하면 지시문의 범위가 부모 범위의 'name'변수에 액세스 할 수 없습니다 (이것은 ng-model을 사용하려고 생각한 이유입니다).
- 지시문에서 ngModel을 제거하고 원하는 이름으로 바꿀 수있는 사용자 정의 이름으로 바꿨습니다.
- 모든 것이 여전히 작동하게 만드는 것은 범위에서 '='기호입니다. 워드 프로세서 체크 아웃 문서를 '범위'헤더 아래.
일반적으로 지시문의 값이 항상 상위 범위의 값에 매핑되도록하려면 지시문이 격리 된 범위 (올바른 작업)를 사용하고 '='유형 범위를 사용해야합니다.
모든 답변을 결합하여 ng-model 속성 으로이 작업을 수행하는 두 가지 방법이 있습니다.
- ngModel을 복사하는 새로운 범위로
- 링크에서 컴파일하는 것과 동일한 범위
var app = angular.module('model', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "Felipe";
$scope.label = "The Label";
});
app.directive('myDirectiveWithScope', function() {
return {
restrict: 'E',
scope: {
ngModel: '=',
},
// Notice how label isn't copied
template: '<div class="some"><label>{{label}}: <input ng-model="ngModel"></label></div>',
replace: true
};
});
app.directive('myDirectiveWithChildScope', function($compile) {
return {
restrict: 'E',
scope: true,
// Notice how label is visible in the scope
template: '<div class="some"><label>{{label}}: <input></label></div>',
replace: true,
link: function ($scope, element) {
// element will be the div which gets the ng-model on the original directive
var model = element.attr('ng-model');
$('input',element).attr('ng-model', model);
return $compile(element)($scope);
}
};
});
app.directive('myDirectiveWithoutScope', function($compile) {
return {
restrict: 'E',
template: '<div class="some"><label>{{$parent.label}}: <input></label></div>',
replace: true,
link: function ($scope, element) {
// element will be the div which gets the ng-model on the original directive
var model = element.attr('ng-model');
return $compile($('input',element).attr('ng-model', model))($scope);
}
};
});
app.directive('myReplacedDirectiveIsolate', function($compile) {
return {
restrict: 'E',
scope: {},
template: '<input class="some">',
replace: true
};
});
app.directive('myReplacedDirectiveChild', function($compile) {
return {
restrict: 'E',
scope: true,
template: '<input class="some">',
replace: true
};
});
app.directive('myReplacedDirective', function($compile) {
return {
restrict: 'E',
template: '<input class="some">',
replace: true
};
});
.some {
border: 1px solid #cacaca;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app="model" ng-controller="MainCtrl">
This scope value <input ng-model="name">, label: "{{label}}"
<ul>
<li>With new isolate scope (label from parent):
<my-directive-with-scope ng-model="name"></my-directive-with-scope>
</li>
<li>With new child scope:
<my-directive-with-child-scope ng-model="name"></my-directive-with-child-scope>
</li>
<li>Same scope:
<my-directive-without-scope ng-model="name"></my-directive-without-scope>
</li>
<li>Replaced element, isolate scope:
<my-replaced-directive-isolate ng-model="name"></my-replaced-directive-isolate>
</li>
<li>Replaced element, child scope:
<my-replaced-directive-child ng-model="name"></my-replaced-directive-child>
</li>
<li>Replaced element, same scope:
<my-replaced-directive ng-model="name"></my-replaced-directive>
</li>
</ul>
<p>Try typing in the child scope ones, they copy the value into the child scope which breaks the link with the parent scope.
<p>Also notice how removing jQuery makes it so only the new-isolate-scope version works.
<p>Finally, note that the replace+isolate scope only works in AngularJS >=1.2.0
</div>
링크 타임에 컴파일이 마음에 들지 않습니다. 그러나 요소를 다른 요소로 바꾸는 경우에는 그렇게 할 필요가 없습니다.
대체로 나는 첫 번째를 선호합니다. 범위를 {ngModel:"="}
설정 ng-model="ngModel"
하고 템플릿에서 원하는 위치를 설정 하면됩니다.
업데이트 : 코드 스 니펫을 인라인하고 Angular v1.2 용으로 업데이트했습니다. 특히 jQuery를 사용하지 않는 경우 격리 범위가 여전히 가장 좋습니다. 따라서 다음과 같이 요약됩니다.
단일 요소를 바꾸는 경우 : 그냥 바꾸고 범위를 그대로 두십시오. 그러나 v2.0에서는 replace가 더 이상 사용되지 않습니다.
app.directive('myReplacedDirective', function($compile) { return { restrict: 'E', template: '<input class="some">', replace: true }; });
그렇지 않으면 이것을 사용하십시오 :
app.directive('myDirectiveWithScope', function() { return { restrict: 'E', scope: { ngModel: '=', }, template: '<div class="some"><input ng-model="ngModel"></div>' }; });
그렇게 복잡하지 않습니다 : 당신의 dirctive에서 별명을 사용하십시오 : scope:{alias:'=ngModel'}
.directive('dateselect', function () {
return {
restrict: 'E',
transclude: true,
scope:{
bindModel:'=ngModel'
},
template:'<input ng-model="bindModel"/>'
}
귀하의 HTML에서 정상적으로 사용하십시오
<dateselect ng-model="birthday"></dateselect>
모델의 $ viewValue 또는 $ modelValue에 액세스해야하는 경우 ng-model 만 필요합니다. NgModelController를 참조하십시오 . 이 경우을 사용 require: '^ngModel'
합니다.
나머지는 Roys answer를 참조하십시오 .
이것은 약간 늦은 답변이지만 에 대한 이 멋진 게시물을 찾았습니다.이 게시물NgModelController
은 정확히 당신이 찾고있는 것 같습니다.
TL; DR- 링크 기능을 사용 require: 'ngModel'
하고 추가 NgModelController
할 수 있습니다.
link: function(scope, iElement, iAttrs, ngModelCtrl) {
//TODO
}
이렇게하면 해킹이 필요하지 않습니다-Angular의 내장 기능을 사용하고 있습니다 ng-model
속성을 통해 ngmodel을 설정하지 않고 템플릿에서 바로 지정할 수 있습니다.
template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',
plunker : http://plnkr.co/edit/9vtmnw?p=preview
Angular 1.5부터 구성 요소를 사용할 수 있습니다. 구성 요소는 이동이 간편하며이 문제를 쉽게 해결합니다.
<myComponent data-ng-model="$ctrl.result"></myComponent>
app.component("myComponent", {
templateUrl: "yourTemplate.html",
controller: YourController,
bindings: {
ngModel: "="
}
});
YourController 안에서해야 할 일은 :
this.ngModel = "x"; //$scope.$apply("$ctrl.ngModel"); if needed
격리 범위를 만드는 것은 바람직하지 않습니다. scope 속성을 사용하지 말고 이와 같은 작업을 수행하십시오. scope : true는 새로운 자식 범위를 제공하지만 격리하지는 않습니다. 그런 다음 구문 분석을 사용하여 로컬 범위 변수가 사용자가 ngModel 속성에 제공 한 것과 동일한 객체를 가리 키도록합니다.
app.directive('myDir', ['$parse', function ($parse) {
return {
restrict: 'EA',
scope: true,
link: function (scope, elem, attrs) {
if(!attrs.ngModel) {return;}
var model = $parse(attrs.ngModel);
scope.model = model(scope);
}
};
}]);
참고 URL : https://stackoverflow.com/questions/14115701/angularjs-create-a-directive-that-uses-ng-model
'development' 카테고리의 다른 글
열거 형 서수에서 열거 형으로 변환 (0) | 2020.03.18 |
---|---|
git에서 브랜치 간의 커밋 차이점을 어떻게 알 수 있습니까? (0) | 2020.03.18 |
여권 직렬화 직렬화 이해 (0) | 2020.03.18 |
파이썬 변수의 유형을 확인하는 가장 좋은 방법은 무엇입니까? (0) | 2020.03.18 |
작은 파비콘이 또 다른 HTTP 요청을 요구하는 것은 어리석지 않습니까? (0) | 2020.03.18 |