code

require : 'ngModel'의 의미는 무엇입니까?

codestyles 2020. 9. 1. 07:32
반응형

require : 'ngModel'의 의미는 무엇입니까?


이것은 내 지시문의 HTML입니다.

<textarea data-modal="modal" data-mydir ng:model="abc"></textarea>

내 지시문에는 다음이 있습니다.

return {
        require: 'ngModel',
        replace: true,
        scope: {
            modal: '=modal',
            ngModel: '=',
            pid: '=pid'
        },

누군가가 require : 'ngModel'의 중요성이 무엇인지 말해 줄 수 있습니까? 나는 이것을 많은 다른 지시에서 본다. 이것을 데이터 모달이라고 부를 수 있습니까?

데이터 모달로 변경하면 Angular에서 다음과 같은 메시지가 표시되기 때문에 혼란 스럽습니다.

Controller 'ngModel', required by directive 'textarea', can't be found!

require명령은 link함수 의 네 번째 인수로 명명 한 지시문에 대한 컨트롤러를 제공합니다 . (당신이 사용할 수있는 ^부모 요소의 컨트롤러를 찾기 위해, ?그것을 선택한다.) 그래서 require: 'ngModel'당신에게를위한 컨트롤러 제공 ngModel지침, 입니다ngModelController .

지시어 컨트롤러는 다른 지시어가 사용할 수있는 API를 제공하도록 작성 될 수 있습니다. 사용하면 값 가져 오기 및 설정을 포함하여에 ngModelController내장 된 특수 기능에 액세스 할 수 있습니다 ngModel. 다음 예를 고려하십시오.

<input color-picker ng-model="project.color">
app.directive('colorPicker', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      element.colorPicker({
        // initialize the color to the color on the scope
        pickerDefault: scope.color,
        // update the ngModel whenever we pick a new color
        onColorChange: function(id, newValue) {
          scope.$apply(function() {
            ngModel.$setViewValue(newValue);
          });
        }
      });

      // update the color picker whenever the value on the scope changes
      ngModel.$render = function() {
        element.val(ngModel.$modelValue);
        element.change();                
      };
    }
  }
});

이 지시문은 ngModel컨트롤러를 사용하여 색상 선택기에서 색상 값을 가져오고 설정합니다. 이 JSFiddle 예제를 참조하십시오 : http://jsfiddle.net/BinaryMuse/AnMhx/

를 사용하는 경우 격리 범위 에서도 사용 require: 'ngModel'해서는 안됩니다 . 당신에게 당신이 값을 변경하는 데 필요한 모든 액세스 할 수 있습니다.ngModel: '='ngModelController

AngularJS 홈페이지 의 맨 아래 예제 에서도이 기능을 사용합니다 (사용자 지정 컨트롤러 사용 제외 ngModel).


As for the casing of a directive, for example, ngModel vs ng-model vs data-ng-model: while Angular supports using multiple forms on the DOM, when you refer to a directive by name (for example, when creating a directive, or using require), you always use the lowerCamelCase form of the name.


As stated in the Creating Custom Directives documentation: (Firstly to your question in the comment)

Can I have a data-ng-model instead?

The answer:

Best Practice: Prefer using the dash-delimited format (e.g. ng-bind for ngBind). If you want to use an HTML validating tool, you can instead use the data-prefixed version (e.g. data-ng-bind for ngBind). The other forms shown above are accepted for legacy reasons but we advise you to avoid them.

Examples:

<my-dir></my-dir>
<span my-dir="exp"></span>
<!-- directive: my-dir exp -->
<span class="my-dir: exp;"></span>

Secondly, what does the ?ngModel represent?

// Always use along with an ng-model
require: '?ngModel',

When using your directive, it forces it to be used along with the attribute/controller ng-model.

The require setting

(Extract from the book AngularJS by Brad Green & Shyam Seshadri)

Other directives can have this controller passed to them with the require property syntax. The full form of require looks like:

require: '^?directiveName'

Options:

  1. directiveName

    This camel-cased name specifies which directive the controller should come from. So if our <my-menuitem> directive needs to find a controller on its parent <my-menu>, we’d write it as myMenu.

  2. ^

    By default, Angular gets the controller from the named directive on the same element. Adding this optional ^ symbol says to also walk up the DOM tree to find the directive. For the example, we’d need to add this symbol; the final string would be ^myMenu.

  3. ?

    If the required controller is not found, Angular will throw an exception to tell you about the problem. Adding a ? symbol to the string says that this controller is optional and that an exception shouldn’t be thrown if not found. Though it sounds unlikely, if we wanted to let <my-menu-item>s be used without a <mymenu> container, we could add this for a final require string of ?^myMenu.


The require:'ngModel' and require:'^ngModel' allow you to inject the model attached to the element or its parent element on which the directive is bound to.

Its basically an easiest way to pass ngModel into the link/compile function instead passing it using a scope option. Once you have access to ngModel, you can change its value using $setViewValue, make it dirty/clean using $formatters, apply watchers, etc.

Below is a simple example to pass ngModel and change its value after 5 seconds.

Demo: http://jsfiddle.net/t2GAS/2/

myApp.directive('myDirective', function($timeout) {
  return {
    restrict: 'EA',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
        ngModel.$render = function() {
            $timeout(function() {
                ngModel.$setViewValue('StackOverflow');  
            }, 5000);                
        };
    }
  };
});

참고URL : https://stackoverflow.com/questions/20930592/whats-the-meaning-of-require-ngmodel

반응형