Reputation: 33
I have been trying to make an input directive, that allows for different input types (eg Interval (min-max), DateTime, Number, Text...). It is very important that whenever the user changes the type of the data, the corresponding input changes its template. I also need to be able to have more than one input on the page (see PLUNKR to better understand).
After a lot of trial and error, and research, I have come to a conclusion that i need to watch the attribute (great-input), replace the template of my input, according to value from selected input type, and compile it. But I am not able to do it in compile function, and my watches are not working properly in link function (i am getting t1,t2).
So, what I need to do is, on change of value in select(type), change the template of input (for simplicity, I have just color coded the different input types).
$scope.$watch('greatInput', function (newVal) {
console.log(newVal);
html = getTemplate(newVal);
$elem.html('').append($compile(html)($scope));
});
This is pretty much the function that should do the work (with some changes, according to where it is implemented), but I cant find the right place for it.
Complete code on: http://plnkr.co/edit/BCuiqg?p=preview
Upvotes: 3
Views: 1106
Reputation: 49590
By far the easiest approach would be to use ng-if
s in the directive template and bind the type of input on the scope:
.directive("greatInput", function(){
return {
template: '<input ng-if="isStr()" type="txt" ng-model="greatInputModel">\
<input ng-if="isInt()" type="number" ng-model="greatInputModel">\
<input ng-if="isDbl()" type="number" ng-model="greatInputModel">',
scope: {
greatInputModel: "=",
greatInputType: "@",
// etc...
},
link: function($scope){
$scope.isStr = function(){
return $scope.greatInputType === "5" || someotherCondition();
}
// same for $scope.isInt and $scope.isDbl
}
}
});
Upvotes: 2