AngularJS: 부모 스코프가 (격리된 스코프를 사용하여) 양방향 바인딩으로 업데이트되지 않음
부모 스코프에 양방향 바인딩된 값을 가진 분리된 스코프를 가진 디렉티브가 있습니다.부모 스코프의 값을 변경하는 메서드를 호출하고 있습니다만, 변경은 디렉티브에 적용되지 않습니다.(양방향 바인딩은 트리거되지 않습니다).이 질문은 매우 유사합니다.
AngularJS: 부모 스코프가 (격리된 스코프를 사용하여) 양방향 바인딩으로 업데이트되지 않음
단, 명령에서 값을 변경하는 것이 아니라 상위 범위에서만 값을 변경합니다.해결책을 읽었더니 다섯 번째 포인트에서 다음과 같이 적혀 있습니다.
The watch() created by the isolated scope checks whether it's value for the bi-directional binding is in sync with the parent's value. If it isn't the parent's value is copied to the isolated scope.
즉, 부모 값이 2로 변경되면 워치가 트리거됩니다.부모값과 지시값이 동일한지 여부를 확인하고 그렇지 않은 경우 지시값으로 복사합니다.좋아, 하지만 내 지시값은 여전히 1...제가 무엇을 빠뜨리고 있나요?
html:
<div data-ng-app="testApp">
<div data-ng-controller="testCtrl">
<strong>{{myValue}}</strong>
<span data-test-directive data-parent-item="myValue"
data-parent-update="update()"></span>
</div>
</div>
js:
var testApp = angular.module('testApp', []);
testApp.directive('testDirective', function ($timeout) {
return {
scope: {
key: '=parentItem',
parentUpdate: '&'
},
replace: true,
template:
'<button data-ng-click="lock()">Lock</button>' +
'</div>',
controller: function ($scope, $element, $attrs) {
$scope.lock = function () {
console.log('directive :', $scope.key);
$scope.parentUpdate();
//$timeout($scope.parentUpdate); // would work.
// expecting the value to be 2, but it is 1
console.log('directive :', $scope.key);
};
}
};
});
testApp.controller('testCtrl', function ($scope) {
$scope.myValue = '1';
$scope.update = function () {
// Expecting local variable k, or $scope.pkey to have been
// updated by calls in the directive's scope.
console.log('CTRL:', $scope.myValue);
$scope.myValue = "2";
console.log('CTRL:', $scope.myValue);
};
});
사용하다$scope.$apply()변경 후$scope.myValue컨트롤러에 다음과 같은 기능이 있습니다.
testApp.controller('testCtrl', function ($scope) {
$scope.myValue = '1';
$scope.update = function () {
// Expecting local variable k, or $scope.pkey to have been
// updated by calls in the directive's scope.
console.log('CTRL:', $scope.myValue);
$scope.myValue = "2";
$scope.$apply();
console.log('CTRL:', $scope.myValue);
};
});
답변: $scope 사용.$syslog()가 완전히 올바르지 않습니다.
지시의 범위를 갱신하는 유일한 방법은 다음과 같습니다.
angular.module('app')
.directive('navbar', function () {
return {
templateUrl: '../../views/navbar.html',
replace: 'true',
restrict: 'E',
scope: {
email: '='
},
link: function (scope, elem, attrs) {
scope.$on('userLoggedIn', function (event, args) {
scope.email = args.email;
});
scope.$on('userLoggedOut', function (event) {
scope.email = false;
console.log(newValue);
});
}
}
});
컨트롤러에서 다음과 같이 이벤트를 내보냅니다.
$rootScope.$broadcast('userLoggedIn', user);
이것은 해킹처럼 느껴집니다만, 각도 전문가가 이 투고를 보고 더 나은 답변을 해 주었으면 합니다만, 받아들여진 답변이기 때문에, 동작조차 하지 않고, 이미 진행중인 에러 $digest를 줄 뿐입니다.
허용된 답변과 같이 $apply()를 사용하면 모든 종류의 버그와 잠재적인 성능 적중도 발생할 수 있습니다.방송 설정 등 많은 작업이 필요합니다.다음 사이클에서 이벤트를 트리거하기 위해 표준 타임아웃을 사용하는 간단한 회피책을 찾았습니다(타임아웃으로 인해 즉시 발생).다음과 같이 parentUpdate() 콜을 둘러싼다.
$timeout(function() {
$scope.parentUpdate();
});
나에게 딱 맞습니다.(주: 0ms가 지정되지 않은 경우 기본 타임아웃 시간)
대부분의 사람들이 잊고 있는 것은 오브젝트 표기법을 사용하여 격리된 스코프를 선언하고 부모 스코프 속성이 바인딩될 것으로 기대할 수 없다는 것입니다.이러한 바인딩은 바인딩 '매직'이 작동하는 속성이 선언된 경우에만 작동합니다.상세한 것에 대하여는, 을 참조해 주세요.
https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/
「 」를 하는 대신에, 「 」를 사용합니다.$scope.$apply() , 을 사용해 .$scope.$applyAsync();
언급URL : https://stackoverflow.com/questions/22557599/angularjs-parent-scope-is-not-updated-in-directive-with-isolated-scope-two-wa
'source' 카테고리의 다른 글
| 워드프레스 필터 문서?add_filter()를 이해하려고 합니다. (0) | 2023.02.14 |
|---|---|
| Angular에서 객체를 푸시하는 방법ngRepeat 어레이 간의 JS (0) | 2023.02.14 |
| WordPress에서 wpdb 클래스를 사용하여 외부 데이터베이스 액세스 (0) | 2023.02.14 |
| 모델이 각도 입력의 날짜 개체가 아닙니다.JS (0) | 2023.02.14 |
| 반응 소품:오브젝트 또는 속성을 전달해야 합니까?차이가 많이 나나요? (0) | 2023.02.14 |