programing tip

ng-model과 ng-bind의 차이점은 무엇입니까

itbloger 2020. 10. 4. 10:38
반응형

ng-model과 ng-bind의 차이점은 무엇입니까


나는 현재 AngularJS와 배우고 사이의 차이를 이해하는 데 어려움을 겪고 ng-bindng-model.

누구든지 그들이 어떻게 다른지 그리고 언제 다른 것을 사용 해야하는지 말해 줄 수 있습니까?


ng-bind 에는 단방향 데이터 바인딩이 있습니다 ($ scope->보기). 변수 이름이있는 html에 삽입 된 {{ val }}범위 값을 표시 하는 바로 가기 있습니다.$scope.valval

ng-model 은 양식 요소 내부에 배치하기위한 것이며 양방향 데이터 바인딩 ($ scope->보기 및보기-> $ scope)이 <input ng-model="val"/>있습니다.


tosh 의 답변은 질문의 핵심에 잘 전달됩니다. 다음은 몇 가지 추가 정보입니다 ....

필터 및 포맷터

ng-bindng-model모두가 사용자를 출력하기 전에 데이터 변환의 개념을 갖는다. 이를 ng-bind위해 필터ng-model사용하고 포맷터사용 합니다 .

필터 (ng-bind)

으로는 ng-bind, 당신은 사용할 수있는 필터를 사용자의 데이터를 변환 할 수 있습니다. 예를 들면

<div ng-bind="mystring | uppercase"></div>,

또는 더 간단하게 :

<div>{{mystring | uppercase}}</div>

참고 uppercase내장되어 각 필터 , 당신은 또한 수 있지만 자신의 필터를 구축 .

포맷터 (ng-model)

ng-model 포맷터를 생성하려면을 수행하는 지시문을 생성하여 require: 'ngModel'해당 지시문이 ngModel의 controller. 예를 들면 :

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$formatters.push(function(value) {
        return value.toUpperCase();
      });
    }
  }
}

그런 다음 부분에서 :

<input ngModel="mystring" my-model-formatter />

이것은 본질적이다 ng-model뭐라고의 해당 uppercase 필터가 에서하고있는 ng-bind위의 예.


파서

이제 사용자가의 값을 변경하도록 허용하려면 어떻게해야 mystring합니까? 모델 -> viewng-bind 에서 단방향 바인딩 만 있습니다 . 그러나 -> 모델 에서 바인딩 할 수 있습니다. 즉, 사용자가 모델의 데이터를 변경하도록 허용 할 수 있으며 파서사용 하여 사용자의 데이터를 간소화 된 방식으로 형식화 할 수 있습니다. 다음과 같이 표시됩니다.ng-model

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
}

ng-model포맷터 / 파서 예제 의 라이브 플 런커로 플레이


다른 무엇입니까?

ng-model또한 기본 제공 유효성 검사가 있습니다. $parsers또는 $formatters함수를 수정하여 ngModelcontroller.$setValidity(validationErrorKey, isValid) 함수를 호출하기 만하면 됩니다 .

Angular 1.3에는$parsers 또는대신 유효성 검사에 사용할 수 있는 새로운 $ validators 배열 이 있습니다$formatters.

Angular 1.3에는 ngModel에 대한 getter / setter 지원도 있습니다.


ngModel

ngModel 지시문은 입력, 선택, 텍스트 영역 (또는 사용자 지정 양식 컨트롤)을 범위의 속성에 바인딩합니다.

이 지시문은 우선 순위 레벨 1에서 실행됩니다.

플 런커

자바 스크립트

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS

.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

<p id="inputDescription">
   Update input to see transitions when valid/invalid.
   Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel은 다음을 담당합니다.

  • 입력, 텍스트 영역 또는 선택과 같은 다른 지시문에 필요한 모델에보기를 바인딩합니다.
  • 유효성 검사 동작 제공 (예 : 필수, 번호, 이메일, URL).
  • 제어 상태 유지 (유효 / 무효, 더티 / 완전, 터치 / 미 손상, 유효성 검사 오류)
  • 애니메이션을 포함하여 요소 (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched)에 관련 CSS 클래스를 설정합니다.
  • 컨트롤을 부모 폼에 등록합니다.

ngBind

ngBind 속성은 지정된 HTML 요소의 텍스트 콘텐츠를 주어진 식의 값으로 바꾸고 해당 식의 값이 변경되면 텍스트 콘텐츠를 업데이트하도록 Angular에 지시합니다.

이 지시문은 우선 순위 레벨 0에서 실행됩니다.

플 런커

자바 스크립트

angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

<div ng-controller="ExampleController">
  <label>Enter name: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

ngBind는 다음을 담당합니다.

  • 지정된 HTML 요소의 텍스트 콘텐츠를 지정된 표현식의 값으로 바꿉니다.

ng-bind또는 사용하는 것을 망설이는 경우 ng-model다음 질문에 답해보십시오.


Do you only need to display data?

  • Yes: ng-bind (one-way binding)

  • No: ng-model (two-way binding)

Do you need to bind text content (and not value)?

  • Yes: ng-bind

  • No: ng-model (you should not use ng-bind where value is required)

Is your tag a HTML <input>?

  • Yes: ng-model (you cannot use ng-bind with <input> tag)

  • No: ng-bind


ng-model

ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.

ng-bind

ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.

This example would help you to understand.


angular.module('testApp',[]).controller('testCTRL',function($scope)
                               
{
  
$scope.testingModel = "This is ModelData.If you change textbox data it will reflected here..because model is two way binding reflected in both.";
$scope.testingBind = "This is BindData.You can't change this beacause it is binded with html..In above textBox i tried to use bind, but it is not working because it is one way binding.";            
});
div input{
width:600px;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<head>Diff b/w model and bind</head>
<body data-ng-app="testApp">
    <div data-ng-controller="testCTRL">
        Model-Data : <input type="text" data-ng-model="testingModel">
        <p>{{testingModel}}</p>
          <input type="text" data-ng-bind="testingBind">
          <p ng-bind="testingBind"></p>
    </div>
</body>


ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.


We can use ng-bind with <p> to display, we can use shortcut for ng-bind {{model}}, we cannot use ng-bind with html input controls, but we can use shortcut for ng-bind {{model}} with html input controls.

<input type="text" ng-model="name" placeholder="Enter Something"/>
<input type="text" value="{{name}}" placeholder="Enter Something"/>
  Hello {{name}}
<p ng-bind="name"</p>

참고URL : https://stackoverflow.com/questions/12419619/whats-the-difference-between-ng-model-and-ng-bind

반응형