Reputation:
I'm trying to figure out if it's possible to get the automatic functionality of attribute binding that you can get from an isolate scope:
scope : { someAttr: '@' }
while retaining the transparent scope-->parentScope property access of scope.$new()
:
$scope.foo = 'foo';
$scope.bar = 'bar';
var childScope = $scope.new();
childScope.foo = 'childFoo';
// childScope == { foo: 'childFoo', bar: 'bar' }
Ideas? I'm not sure how to create a new scope in the controller and then send attributes from a directive to that... ???
To be clear I ultimately want in a controller:
$scope === {
attr : << attribute from directive instance >>
, parentKey : << transparent to parent diretive's scope >>
}
Upvotes: 1
Views: 77
Reputation: 43023
It's actually really simple to do this yourself. You use the $parse
service to turn an expression into a function, then just expose that function on the scope.
What Angular does internally when it encounters an &
scope in the directive code is just this: https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L892-L898
So you could just make a small helper function which does this three-liner for you on properties that you want.
/*
* Creates a child scope, turning the property names in the whatToGetter
* array into getters
* @param parentScope scope to inherit
* @param whatToGetter array of string properties to turn into getters
* of the parent on the child scope
* @returns scope new child scope
*/
function childScope(parentScope, whatToGetter) {
var child = parentScope.$new();
angular.forEach(whatToGetter, function(property) {
var getter = $parse(parentScope[property]);
child[property] = function() {
return getter(parentScope);
};
});
return child;
}
var scope = {foo: '1', bar: '2'};
var child = childScope(scope, ['bar']);
console.log(child.foo); // --> 1
console.log(child.bar()); // --> 2
Upvotes: 1