What's the meaning of require: 'ngModel'?

前端 未结 3 810
挽巷
挽巷 2020-11-28 03:02

This is the HTML for my directive:


In my directive I hav

3条回答
  •  借酒劲吻你
    2020-11-28 03:45

    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:

    
    
    
    
    

    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 directive needs to find a controller on its parent , 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 s be used without a container, we could add this for a final require string of ?^myMenu.

提交回复
热议问题