Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 680
albttx Avatar asked Oct 18 '22 03:10

albttx


2 Answers

There seems to be a misunderstanding. .component will always create it's own, isolated scope and you simply don't use $scope in components. If you think it's absolutely necessary in your case, then use .directive. I recommend to redesign your component appropriately though.

like image 117
a better oliver Avatar answered Oct 26 '22 23:10

a better oliver


You don't need to use $scope.$new() in your case because $compile is 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.

like image 27
Dev Avatar answered Oct 27 '22 01:10

Dev