UPDATE
Acknowledging the insightful comments, utilizing this in conjunction with ng-change necessitates a preliminary "dummy" ng-model to already exist. It is worth mentioning that as of version 1.3, the framework seems to have integrated the required options. For more details, refer to this link.
/UPDATE
If you find yourself encountering a straightforward scenario amidst a more intricate task, here is the approach I devised for dynamically associating arbitrary expressions with ng-model: this code snippet.
Approach: I formulated a directive named dynamicModel that processes a standard Angular expression, evaluates it, and binds the outcome to the scope using ng-model and $compile.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.testvalue = 'data.foo';
$scope.eval = $scope.$eval;
});
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {};
$scope.testvalue = 'data.foo';
$scope.eval = $scope.$eval;
});
app.directive('dynamicModel', ['$compile', function ($compile) {
return {
'link': function(scope, element, attrs) {
scope.$watch(attrs.dynamicModel, function(dynamicModel) {
if (attrs.ngModel == dynamicModel || !dynamicModel) return;
element.attr('ng-model', dynamicModel);
if (dynamicModel == '') {
element.removeAttr('ng-model');
}
// Unbind all previous event handlers, this is
// necessary to remove previously linked models.
element.unbind();
$compile(element)(scope);
});
}
};
}]);
The usage is quite straightforward: dynamic-model="angularExpression" where angularExpression yields a string utilized as the expression for ng-model.
I trust that sharing this solution might alleviate someone's challenges and prevent unnecessary frustration.
Best regards,
Justus