How do I set the value property in AngularJS' ng-options?

后端 未结 27 1181
感动是毒
感动是毒 2020-11-22 08:17

Here is what seems to be bothering a lot of people (including me).

When using the ng-options directive in AngularJS to fill in the options for a &

27条回答
  •  迷失自我
    2020-11-22 08:43

    It appears that ng-options is complicated (possibly frustrating) to use, but in reality we have an architecture problem.

    AngularJS serves as an MVC framework for a dynamic HTML+JavaScript application. While its (V)iew component does offer HTML "templating," its primary purpose is to connect user actions, via a controller, to changes in the model. Therefore the appropriate level of abstraction, from which to work in AngularJS, is that a select element sets a value in the model to a value from a query.

    • How a query row is presented to the user is the (V)iew’s concern and ng-options provides the for keyword to dictate what the contents of the option element should be i.e. p.text for p in resultOptions.
    • How a selected row is presented to the server is the (M)odel’s concern. Therefore ng-options provides the as keyword to specify what value is provided to the model as in k as v for (k,v) in objects.

    The correct solution this is problem is then architectural in nature and involves refactoring your HTML so that the (M)odel performs server communication when required (instead of the user submitting a form).

    If an MVC HTML page is unnecessary over-engineering for the problem at hand: then use only the HTML generation portion of AngularJS’s (V)iew component. In this case, follow the same pattern that is used for generating elements such as <li />'s under <ul />'s and place a ng-repeat on an option element:

    
    

    As kludge, one can always move the name attribute of the select element to a hidden input element:

    
    
    

提交回复
热议问题