카테고리 없음
[자바 스크립트] 부모 범위 속성과 격리 된 범위 속성을 동기화하는 방법은 무엇입니까?
필살기쓰세요
2021. 1. 21. 18:53
뭔가 잘못한 게 분명합니다. 양방향 바운드 인 경우 양방향 바운드입니다.
function MainController() {
this.name = "test";
this.logCtrlName = function() {
alert(this.name);
}
}
function dynamicField() {
return {
restrict: 'E',
template: `
<div class="field">
<input type="text" ng-model="ngModel" />
</div>
`,
scope: {
ngModel: '='
}
};
}
angular.module('app', []);
angular.module('app')
.controller('MainController', MainController)
.directive('dynamicField', dynamicField);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainController as ctrl">
<dynamic-field name="Name" type="input" ng-model="ctrl.name"></dynamic-field>
<a href ng-click="ctrl.logCtrlName();">Name inside parent controller</a>: {{ ctrl.name | json }}
</div>
</div>
스 니펫 확장
모델이 원시 값이기 때문에 말했듯이 격리 된 범위 내에서 값을 변경할 때마다 범위 변수의 복사본이 생성됩니다.
수정하는 간단하고 빠른 방법은 상위 범위 값을 $scope.$parent.ngModel
직접 업데이트하는 함수를 만든 다음 ng-change
입력 요소에 추가 하고 입력 값이 변경 될 때마다 해당 함수를 호출하는 것입니다.
출처
https://stackoverflow.com/questions/39917023