programing

ng-model에서의 패스 함수

subpage 2023. 3. 5. 09:48
반응형

ng-model에서의 패스 함수

예를 들어 함수를 ng-model로 전달할 수 있습니까?

<input type="text" name="email" class="form-control" ng-model="createModel('email')" ng-change="addProperty(email,'email')" email required placeholder="Email">

ng-change는 정상적으로 동작하고 있습니다만,ng-model="createModel(email)"이 에러를 나타내고 있습니다.

> Expression 'createModel('email')' is non-assignable. Element: <input
> type="text" name="email"....

controller에는 : // 일단 값을 전달하고 싶습니다.

  $scope.createModel = function(modelName){
     console.log("Model name"+modelName);
  }

나는 인터넷에서 사람들이 이것을 하는 예를 보았다.

각진 모양JS는 버전 1.3에서 "getter" "setter" 지원을 추가했습니다.

다음 URL에서 ngModel 문서 페이지 맨 아래로 스크롤할 수 있습니다.

https://docs.angularjs.org/api/ng/directive/ngModel

이를 통해 ngModel 속성에 변수 대신 메서드를 지정할 수 있습니다.메서드는 선택적 매개 변수를 사용해야 합니다.인수가 전달되면 해당 값이 저장되고 인수가 전달되지 않으면 값이 반환됩니다.

다음 URL에서 다른 스택오버플로우 응답 예를 볼 수 있습니다.https://stackoverflow.com/a/28224980/984780

함수를 에 전달할 수 없습니다.ng-modelAngular는 사용자가 입력 값을 변경할 때 값을 설정할 수 있어야 하기 때문입니다.값이 변경될 때 대신 함수를 호출하도록 Angular에게 지시할 수 없습니다.getter 및 setter 메서드를 사용하여 스코프에서 다음과 같은 속성을 정의할 수 있습니다.

var email = 'test@test.com';
Object.defineProperty($scope, 'email', {
  get: function() {
    return email;
  },
  set: function(value) {
    email = value;
  }
});

하지만 다른 Angular 개발자들에게는 더 친숙하기 때문에 $watch를 만드는 것이 좋습니다.

편집: 다른 값에 따라 다른 모델에 바인드하는 경우에도 동일한 속성에 바인드할 수 있습니다.ng-model단, 시계로 교환할 수 있습니다.다음과 같은 경우:

var model1 = {
  value: 'hi'
};
var model2 = {
  value: 'hello'
};
$scope.model = model1;

$scope.checkboxValue = true;
$scope.$watch('checkboxValue', function(value) {
  if (value) {
    $scope.model = model1;
  } else {
    $scope.model = model2;
  }
});

그리고:

<input type="text" ng-model="model.value">
<input type="checkbox" ng-model="checkboxValue">

그러면 체크박스가 켜져 있는지 여부에 따라 텍스트 입력 값이 변경됩니다.

언급URL : https://stackoverflow.com/questions/22373562/pass-function-in-ng-model

반응형