ng-repeat 내에서 Ng-click이 작동하지 않음
ng-repeat 내부에서는 Ng-click이 작동하지 않습니다.밖에서는 효과가 있다.여기에 바이올린을 켰다.
<div ng-controller="MyCtrl">
<a ng-click="triggerTitle='This works!'">test</a>
<h5>Please select trigger event: [{{triggerEvent}}] {{triggerTitle}}</h5>
<ul class="dropdown-menu">
<li ng-repeat="e in events">
<a ng-click="triggerTitle=e.name; triggerEvent = e.action;">{{e.action}} - {{e.name}}</a>
</li>
</ul>
</div>
벤이 말했듯이ng-repeat는 루프 내의 각 항목에 대해 자 스코프를 작성합니다.하위 스코프는 프로토타입 상속을 통해 상위 스코프의 변수 및 메서드에 액세스할 수 있습니다.헷갈리는 부분은 할당을 할 때 상위 범위의 속성을 업데이트하는 대신 하위 범위에 새 변수가 추가된다는 것입니다.인ng-click할당 콜을 발신하는 경우tiggerTitle =e.name, 이것은 실제로 라고 하는 새로운 변수를 추가합니다.triggerTitle자녀 범위로 이동합니다.앵귤러JS docs는 JavaScript Prototypepal Inheritance라는 섹션에서 이를 잘 설명합니다.
그러면 어떻게 하면 이 문제를 해결하고 모델 변수를 올바르게 설정할 수 있을까요?
빠르고 지저분한 해결책은 다음과 같은 방법으로 부모 스코프에 접속하는 것입니다.$parent그렇게.
<a ng:click="$parent.triggerTitle=e.name; $parent.triggerEvent = e.action;">...
클릭하시면 $parent 솔루션을 사용하는 Feelen의 동작 버전을 보실 수 있습니다.
의 사용$parent는 네스트된 템플릿 또는 네스트된ng-module을 취급하는 경우 문제를 일으킬 수 있습니다.더 나은 해결책은 컨트롤러 범위에 대한 참조를 반환하는 기능을 컨트롤러 범위에 추가하는 것입니다.이미 설명한 바와 같이 하위 스코프는 상위 함수를 호출할 수 있으므로 컨트롤러의 스코프를 참조할 수 있습니다.
function MyCtrl($scope) {
$scope.getMyCtrlScope = function() {
return $scope;
}
...
<a ng-click="getMyCtrlScope().triggerTitle=e.name;getMyCtrlScope().triggerEvent = ...
클릭하시면 더 나은 방법을 사용하고 있는 Feelen의 작동 버전을 보실 수 있습니다.
왜냐면ng-repeat새로운 스코프가 생성됩니다.
이것은 여러 번 답변되었습니다.왜냐하면 뉘앙스는 이해하기 어렵기 때문입니다.특히 js의 프로토타입 상속의 모든 것을 모르는 경우:https://github.com/angular/angular.js/wiki/Understanding-Scopes
편집: 이 답변은 매우 논란이 많은 것 같습니다.확실히 하자면, JS는 이렇게 동작합니다.JS의 구조를 이해하기 전에 Angular를 배우려고 하면 안 됩니다.다만, 링크가 누락되어 있는 것 같습니다.
이 경우 JS의 동작 예를 다음에 나타냅니다.
var a = {value: 5};
var b = Object.create(a); // create an object that has `a` as its prototype
// we can access `value` through JS' the prototype chain
alert(b.value); // prints 5
// however, we can't *change* that value, because assignment is always on the designated object
b.value = 10;
alert(b.value); // this will print 10...
alert(a.value); // ... but this will print 5!
그럼 어떻게 대처해야 할까요?
상속 체인을 "강제"할 수 있기 때문에 값에 액세스하든 수정하든 항상 올바른 개체에 액세스할 수 있습니다.
var a = {obj: {value: 5}};
var b = Object.create(a); // create an object that has `a` as its prototype
// we can access `value` through JS' the prototype chain:
alert(b.obj.value); // prints 5
// and if we need to change it,
// we'll just go through the prototype chain again:
b.obj.value = 10;
// and actually refer to the same object!
alert(b.obj.value == a.obj.value); // this will print true
이것 대신:
<li ng-repeat="e in events">
<a ng-click="triggerTitle=e.name; triggerEvent = e.action;">{{e.action}} {{e.name}}</a>
</li>
다음 작업을 수행합니다.
<li ng-repeat="e in events">
<a ng-click="$parent.triggerTitle=e.name; $parent.triggerEvent = e.action;">{{e.action}} {{e.name}}</a>
</li>
ng-repeat스코프를 .그러면, 을 사용할 수 .$parent 할 수 합니다.ng-repeat
여기서 $parent를 사용하면 ng-repeat 이외의 코드에 액세스할 수 있습니다.
HTML 코드
<div ng-controller="MyCtrl">
<a ng-click="triggerTitle='This works!'">test</a>
<h5>Please select trigger event: [{{triggerEvent}}] {{triggerTitle}}</h5>
<br /> <br />
<ul class="dropdown-menu">
<li ng-repeat="e in events">
<a ng-click="$parent.triggerTitle=e.name; $parent.triggerEvent = e.action;">{{e.action}} - {{e.name}}</a>
</li>
</ul>
각도 Js 코드
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.triggerTitle = 'Select Event';
$scope.triggerEvent = 'x';
$scope.triggerPeriod = 'Select Period';
$scope.events = [{action:'compare', name:'Makes a policy comparison'}, {action:'purchase', name:'Makes a purchase'},{action:'addToCart', name:'Added a product to the cart'}]
}
http://jsfiddle.net/xVZEX/96/ 에서 테스트 할 수 있습니다.
이 동작
<body ng-app="demo" ng-controller="MainCtrl">
<ul>
<li ng-repeat="action in actions" ng-click="action.action()">{{action.name}}</li>
</ul>
<script>
angular.module('demo', ['ngRoute']);
var demo = angular.module('demo').controller('MainCtrl', function ($scope) {
$scope.actions = [
{ action: function () {
$scope.testabc();
}, name: 'foo'
},
{ action: function () {
$scope.testxyz();
}, name: 'bar'
}
];
$scope.testabc = function(){
alert("ABC");
};
$scope.testxyz = function(){
alert("XYZ");
};
});
</script>
</body>
ng-repeat이 그 안에서 자신만의 범위를 만드는 문제에 대한 해답을 찾기 위해 오랫동안 인터넷 서핑을 했다.ng-반복 내에서 변수를 변경할 때, 보기는 문서의 다른 모든 위치에서 업데이트되지 않습니다.
결국 제가 찾은 해답은 단어 하나였습니다. 아무도 말해주지 않았습니다.
변수 이름 앞에는 $parent이고 글로벌 범위에서 값이 변경됩니다.
그렇게
ng-click="entryID=1"
ng-click="$parent.entryID=1"
이것을 사용하다
<div ng:controller="MyCtrl">
<a ng:click="triggerTitle='This works!'">test</a>
<h5>Please select trigger event: [{{triggerEvent}}] {{triggerTitle}}</h5>
<ul class="dropdown-menu">
<li ng:repeat="e in events">
<a ng:click="triggerTitle=e.name; triggerEvent = e.action;">{{e.action}} - {{e.name}}</a>
</li>
</ul>
</div>
ng-click을 ng:click으로 변환하고 동작하기 시작했습니다.이유는 아직 찾을 수 없습니다.그냥 바로 공유하기 위해서 투고했습니다.
'as' 키워드와 함께 컨트롤러를 사용합니다.
컨트롤러의 angularjs에 대한 설명서를 참조하십시오.
상기 질문의 경우:
<div ng-controller="MyCtrl as myCntrl">
<a ng-click="myCntrl.triggerTitle='This works!'">test</a>
<h5>Please select trigger event: [{{myCntrl.triggerEvent}}] {{myCntrl.triggerTitle}}</h5>
<ul class="dropdown-menu">
<li ng-repeat="e in myCntrl.events">
<a ng-click="myCntrl.triggerTitle=e.name; myCntrl.triggerEvent = e.action;">{{e.action}} - {{e.name}}</a>
</li>
</ul>
</div>
그러면 컨트롤러의 범위에 속성과 기능이 연결됩니다.
언급URL : https://stackoverflow.com/questions/16736804/ng-click-doesnt-work-inside-ng-repeat
'programing' 카테고리의 다른 글
| Mongo Shell - 콘솔/디버깅 로그 (0) | 2023.03.11 |
|---|---|
| Wordpress 페이지에 Angular 앱을 삽입하려면 어떻게 해야 합니까? (0) | 2023.03.11 |
| Java Spring Security - 사용자.withDefaultPasswordEncoder()는 권장되지 않습니다. (0) | 2023.03.11 |
| AngularJs의 날짜 필터별 내림차순 (0) | 2023.03.11 |
| Redux에서는 상세 복사가 필요합니까? (0) | 2023.03.11 |