I'm trying to dynamically generate an ng-model directive using a filter. The main idea is that there is some text in a database. This text has gaps defined by numbers between square brackets ([1], [2], etc.). The purpose is to parse those gaps and turn them into inputs. These inputs should be then binded to a variable using the ng-model directive but I can't get it to work.
Here is my controller:
app.controller('exerciseTemplateCtrl', ['$http', '$scope', '$sce', '$filter', '$compile', function($http, $scope, $sce, $filter, $compile){
// used to test the binding through ng-model
$scope.answers = [];
$http.get('encode_exercises.json')
.then(function(response){
$scope.firstExercise = response.data;
});
$scope.parseHtml = function(input){
input = $filter('gapToInput')(input);
return $sce.trustAsHtml(input);
};
}]);
Here my filter 'gapToInput'
app.filter('gapToInput', function(){
return function(input){
return input.replace(/\[[0-9]\]/g, '<input type="text" ng-model="answers">');
};
});
As you can see I am binding the model using the "answers" variable. Here is my directive:
app.directive('exerciseTemplate', function(){
return{
restrict: 'E',
templateUrl: 'exercise-template.html'
};
});
The index.html contains the previous directive:
<exercise-template></exercise-template>
And here my template for the previous directive (simplified)
<div ng-controller="exerciseTemplateCtrl as e">
<div ng-repeat="exercise in firstExercise">
<div ng-repeat="(questionId, question) in exercise.q">
<div ng-bind-html="parseHtml(question.d.q)"></div>
</div>
</div>
<p><button>Check</button></p>
</div>
question.d.q contains the text from the database with the gaps ([1], [2], etc.) and it's applying the filter successfully (apologies, I don't have enough reputation to post images):
https://i.stack.imgur.com/W0NoI.png
The problem is that, even if the replacement works, the ng-model directive is not binding each input with the "answers" variable. For what I've been reading, this is because I have to recompile again the template so that Angular parses all of the ng-directives again. Tried doing the following without any luck:
var scope = $scope;
$scope.parseHtml = function(input){
input = $filter('gapToInput')(input);
input = $compile(input)(scope);
return $sce.trustAsHtml(input);
};
I've also followed this thread and tried changing the directive format to the following:
app.directive('exerciseTemplate', ['$compile', '$http', function($compile, $http){
return {
restrict: 'E',
link: function(scope, element, attrs){
$http.get('exercise-template.html').then(function(result){
element.replaceWith($compile(result.data)(scope));
});
}
}
}]);
But it's still not binding the model. I'm starting to feel a bit frustrated of how difficult Angular is even with the simplest things so any help would be really appreciated.
Thanks