itsource

angularjs에서의 조건부 ng-model 바인딩

mycopycode 2023. 2. 26. 09:44
반응형

angularjs에서의 조건부 ng-model 바인딩

복잡하고 단순한 요소를 처리해야 하는 어레이 모델이 있습니다.

{
    "object" :[
               "element1.html",
               "element2.html",
               {
                   "url:"element3.html",
                   "title" : "Title 3"
               },
               "element4.html",
               "element5.html"
            ]
}

angularjs(콤플렉스 URL 표시)에서 심플한 요소와 복잡한 요소를 모두 처리할 수 있는 선택 방법이 있습니까?

어프로치 1

내 말은, 그런 것들 말이야.

ng-model="(object[$index].url ? object[$index].url : object[$index])"

어프로치 2

빈 배열과 가 단순한지 복잡한지를 나타내는 파일 형식을 사용하여 각 개체의 복잡한 구조를 갖는 정규화된 개체를 만듭니다.

두 번째 접근을 피하기 위해 각진 마법을 써도 될까요?

감사합니다!

사용할 수 있습니다.ngSwitch또는ngIf올바른 요소를 배치합니다.

예를 들어 ngIf를 사용하는 경우:

<input ngIf="object[$index].url" ngModel="object[$index].url">
<input ngIf="!object[$index].url" ngModel="object[$index]">

조건이 충족되지 않으면 angular는 조건이 충족될 때까지 돔 요소를 완전히 제거합니다.

게터 및 세터 사용

오브젝트에 getters와 setters를 정의하고 그 안에 로직을 넣어 조건부로 취득/수정하고 싶은 다른 오브젝트를 취득/설정할 수 있습니다.

Angular에는 다음과 같이 사용할 수 있는 가 있습니다.

input(ng-model="data" ng-model-options="{getterSetter:true}")

var data1 = "data 1";
var data2 = "data 2";
$scope.data = function(newVal) {
    if (condition) {
        if (angular.isDefined(newVal))
            data1 = newVal;
        return data1;
    } else {
        if (angular.isDefined(newVal))
            data2 = newVal;
        return data2;
    }
};

하지만, 저만의 경우일 수도 있고, 그것만으로는 효과가 없었거나, 기대했던 대로 되지 않았습니다.

JavaScript의 디폴트 방식도 있습니다.Object.defineProperty

var data1 = "data 1";
var data2 = "data 2";
Object.defineProperty($scope, 'data', {
    get: function() {
        if(condition)
            return data1;
        else
            return data2;
    },
    set: function(newVal) {
        if(condition)
            data1 = newVal;
        else
            data2 = newVal;
    }
});

이것도 제 경우일 수도 있지만 둘 중 하나만 사용해도 제대로 작동하지 않거나 예상대로 작동하지 않았습니다.그래서 둘 다 같이 썼는데 완벽하게 작동해요.

언급URL : https://stackoverflow.com/questions/23107788/conditional-ng-model-binding-in-angularjs

반응형