Skip to content

Instantly share code, notes, and snippets.

@djdmbrwsk
Created July 16, 2015 18:29
Show Gist options
  • Save djdmbrwsk/9a7004492a709044e597 to your computer and use it in GitHub Desktop.
Save djdmbrwsk/9a7004492a709044e597 to your computer and use it in GitHub Desktop.
Dynamically set ng-model with an expression
(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);
}
};
}
]);
})();
@aspecker
Copy link

This is exactly what I needed, thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment