javascript - AngularJS directive runtime template change -
i have been trying make input directive, allows different input types (eg interval (min-max), datetime, number, text...). important whenever user changes type of data, corresponding input changes template. need able have more 1 input on page (see plunkr better understand).
after lot of trial , error, , research, have come conclusion need watch attribute (great-input), replace template of input, according value selected input type, , compile it. not able in compile function, , watches not working in link function (i getting t1,t2).
so, need is, on change of value in select(type), change template of input (for simplicity, have color coded different input types).
$scope.$watch('greatinput', function (newval) { console.log(newval); html = gettemplate(newval); $elem.html('').append($compile(html)($scope)); });
this pretty function should work (with changes, according implemented), cant find right place it.
complete code on: http://plnkr.co/edit/bcuiqg?p=preview
by far easiest approach use ng-if
s in directive template , bind type of input on 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 $scope.isint , $scope.isdbl } } });
Comments
Post a Comment