I want to populate a form with some dynamic questions (fiddle here):
<div ng-app ng-controller="QuestionController">     <ul ng-repeat="question in Questions">         <li>             <div>{{question.Text}}</div>             <select ng-model="Answers['{{question.Name}}']" ng-options="option for option in question.Options">             </select>         </li>     </ul>      <a ng-click="ShowAnswers()">Submit</a> </div>  function QuestionController($scope) {     $scope.Answers = {};      $scope.Questions = [     {         "Text": "Gender?",         "Name": "GenderQuestion",         "Options": ["Male", "Female"]},     {         "Text": "Favorite color?",         "Name": "ColorQuestion",         "Options": ["Red", "Blue", "Green"]}     ];      $scope.ShowAnswers = function()     {         alert($scope.Answers["GenderQuestion"]);         alert($scope.Answers["{{question.Name}}"]);     }; }   Everything works, except the model is literally Answers["{{question.Name}}"], instead of the evaluated Answers["GenderQuestion"]. How can I set that model name dynamically?
In basic examples, AngularJS uses the $scope object as the model. However, in the previous article I showed how using the controllerAs method allowed the controller itself to be added to the scope with a given name and essentially be used as the model.
ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form.
NgModel expects the bound element to have a value property, which div s don't have. That's why you get the No value accessor error. I don't know if the input event is supported on all browsers for contenteditable . You could always bind to some keyboard event instead.
http://jsfiddle.net/DrQ77/
You can simply put javascript expression in ng-model.
You can use something like this scopeValue[field], but if your field is in another object you will need another solution.
To solve all kind of situations, you can use this directive:
this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {     return {         restrict: 'A',         terminal: true,         priority: 100000,         link: function (scope, elem) {             var name = $parse(elem.attr('dynamic-model'))(scope);             elem.removeAttr('dynamic-model');             elem.attr('ng-model', name);             $compile(elem)(scope);         }     }; }]);   Html example:
<input dynamic-model="'scopeValue.' + field" type="text"> 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With