Expose isolated scope binding API #8338
Description
This is a feature request.
The issue
There are various scenarios where one would like to bind models on a child scope ( scope: true
) like on an isolated scope (scope: {}
).
For instance consider the following:
<input ng-model="selected" typeahead />
The typeahead
directive would normally use ngModelController
to deal with the model. But sometimes it would like to bound the model to its scope, so to delegate it to sub-directives (in its template).
If the typeahead
directive uses an isolated scope, it can easily bind to the model using:
scope: {
selected: '=ngModel'
}
But the directive may wish to have a child scope so to see many related models on the parent directive, and there isn't a straight-forward way to bind to the model provided by ngModel
.
Ways to achieve this
There are various ways to achieve this:
Via ngModelController
One can use the input formatters with $parse to get and set the model provided. But this will only work for ngModel
.
Like ngModelController
One can take the same route as ngModelController
:
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign,
Double watching
As anagelc proposes in this issue one can do something like this:
// Bring in changes from outside:
scope.$watch('model', function() {
scope.$eval(attrs.ngModel + ' = model');
});
// Send out changes from inside:
scope.$watch(attrs.ngModel, function(val) {
scope.model = val;
});
But depending on the model, this may fail.
Using a custom service
Another solution would be similar to that proposed by basarat on the same issue as above - a custom service, which essentially exposes code currently in $compile.
Exposing the bind API.
The question is, why not just expose the same methods in $compile used for isolated scope binding to all, essentially allowing us to write something like this:
$scope.selected = $scope.$bind('=ngModel');