How to assign ng-model value in template
-
21-12-2019 - |
Question
I am trying to make ng-repeat
safe pagedown editor in simpler way using a template in a directive.
This is the demo.
http://plnkr.co/edit/TOhGV4?p=preview
As you see from the following code, I bind two variables
- uniqNum
- and, modelName
This is the code.
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
$scope.arr = ["1234567"];
});
app.directive('pagedownEditor', function($compile, $timeout) {
var num=0;
return {
template:
'<div class="wmd-panel">'+
'<div id="wmd-button-bar-{{uniqNum}}"></div>'+
'<textarea ng-model="modelName" class="wmd-input" id="wmd-input-{{uniqNum}}">'+
'</textarea>'+
'</div>'+
'<div id="wmd-preview-{{uniqNum}}" class="pagedown-preview wmd-panel wmd-preview">'+
'</div>',
link: function(scope, iElement, attrs) {
if (scope.$index !== undefined) {
//the following returns 'arr[0]'
scope.modelName = Object.keys(scope.$parent).filter(function(el) {
return (el[0]!=='$' && el !== "this")
})[0] + '[' + scope.$index + ']';
scope.uniqNum = scope.$index;
} else if (attrs.ngModel) {
scope.modelName = attrs.ngModel;
scope.uniqNum = num++;
}
var converter = Markdown.getSanitizingConverter();
var editor = new Markdown.Editor(converter, "-" + scope.$index);
$timeout(function() {editor.run();});
}
};
});
I have no problem setting uniqNum using {{uniqNum}}
However, if I set ng-model="{{modelName}}"
, I have an error, Error: [$parse:syntax]
.
If I set ng-model="modelName"
, no error but ng-model value is modelName itself.
It should show 1234567
instead of variable name arr[0]
in textarea.
From the above code, how do I set ng-model="arr[0]"
using template?
Solution
Demo http://plnkr.co/edit/hFpWgI?p=preview
Basically you can use $compile
to generate dynamic template according to the existence of $index
property on scope. If $index
is defined, the directive is inside a ng-repeat
.
Also you have to use track by
expression in ng-repeat="str in arr track by $index"
. If not, every time value of arr[0] changes will cause ng-repeat to re-render the DOM.