1

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 >>
}
3
  • docs.angularjs.org/api/ng.$rootScope.Scope#$new Take a look at the first parameter :-) Commented Jun 3, 2013 at 11:57
  • @AndyJoslin -- Yeah, that's the opposite of what I want. I'm trying to figure out how to attach a directive's element to a new non-isolate scope Commented Jun 3, 2013 at 12:27
  • Ahh I see... sorry.. I'll make an answer :) Commented Jun 3, 2013 at 12:53

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

That still doesn't explain how to get data from the specific directive instance into the new scope (in a controller) without having multiple similar directives colliding. The issue is that each controller instance will start with the same scope, so when I assign anything to the scope from the directive I have no way of telling which controller instance it's going to
nevermind... it's the freakin' 4th argument passed to link. I feel stupid now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.