Created
July 16, 2015 18:29
-
-
Save djdmbrwsk/9a7004492a709044e597 to your computer and use it in GitHub Desktop.
Dynamically set ng-model with an expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
/* | |
PROBLEM: | |
<input type="text" ng-model="{{someExpressionThatReturnsTheStringYouWant}}"> | |
^ THIS WON'T WORK | |
SOLUTION: | |
<input type="text" ng-model-dynamic="{{someExpressionThatReturnsTheStringYouWant}}"> | |
WARNING: | |
Will only work once, NOT each time the expression produces a different | |
value. Also note that $observe isn't a resolution because after the | |
first recompile there is no more attrs.ngModelDynamic | |
*/ | |
angular.module('myApp') | |
.directive('ngModelDynamic', ['$compile', | |
function ($compile) { | |
return { | |
restrict: 'A', | |
link: function (scope, element, attrs) { | |
// Remove ng-model-dynamic to prevent recursive compilation | |
element.removeAttr('ng-model-dynamic'); | |
// Add ng-model with a value set to the now evaluated expression | |
element.attr('ng-model', attrs.ngModelDynamic); | |
// Recompile the entire element | |
$compile(element)(scope); | |
} | |
}; | |
} | |
]); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is exactly what I needed, thank you