PandaCool PandaCool - 3 months ago 9
AngularJS Question

Angular get new scope through another component

I am building a component based app project with angular 1.5.5

I am creating with d3js some

.floating-node
and for each i create a new $scope and append inside a compiled component.

This part of the code look like :

nodeEnter.each(() => {
let childScope = this.$scope.$new();
childScope.test = "test";
let compiled = this.$compile('<mycomponent></mycomponent>')(childScope);
(this.mainContainer).append(compiled);
});


This part of the code work perfectly.

And this is
mycomponent


export default class Mycomponent {
constructor($scope) {
console.log($scope.test); // undefined
console.log($scope.$parent.test); // test
}
}
Mycomponent.$inject = ["$scope"];


But when I get in my
mycomponent
component. I can't get the right
$scope
.

I checked the
$id
and understand that the
childScope.$id
is in
Mycomponent
$scope.$id += 1


I know I can get through with
$scope.$parent
but I will create undesirable
$scope
, and it's not really appreciated in a loop.

So how can I get the same
$scope
?

Answer

You don't need to use $scope.$new() in your case because $compileis already creating a new instance of scope.

The easier way to solve your issue is to use a querySelector, I guess doing something like the following code should help you :

newScope = angular.element(document.querySelector("#myId")).isolateScope();

This way you should now be able to pass data through newScope.