Search code examples
angularjsangularjs-directiveangular-ngmodeltypeahead

When should ng-model be used as opposed to binding to a property in angularjs?


I am building a directive that I will be using in several places in my application. It is a combination of a multi-select field and type-ahead. To pass data back and forth to the multi-select portion, I need to either use ng-model or a scope property on which I will two-way bind.

Are there distinct advantages to using ng-model over the two-way binding? Are there disadvantages?


Solution

  • I had to make a decision, so here is what I came up with. I ended up going with the simpler two-way-bind solution for now.

    Here are advantages to using ng-model

    • You can provide validation behavior
    • Separates the model and the view as it holds the model off of the scope so changes in the component do not have to immediately be reflected outside of the control
    • It sets css classes on the element for animation and validation purposes.
    • You don't have to pick a name
      • we often end up with names like these: "model", "items", or "data"
    • You can use ngModelOptions to customize ngModel behaviors. For example easy to use debouncing.

    Here are a few disadvantages

    • Pass by reference means that ng-model does not recognize array or object changes.
    • It is simply more complicated, this is the big reason.