Ad

Getting Data From An Angularjs Component In The Script Tag In The Template.html File

- 1 answer

The component file gets data from a csv file and it has a templateUrl to another html file. This html file contains a script tag in which some functionality takes place. I want to access the array from the response.data in the component file in the script tag in the HTML file.

angular.module("keyMetric",[])
.component("keyMetric",{
    templateUrl : 'keymetric/keymetric.template.html',
    controller : function control($http) {
        $http.get('customers.csv').then(function(response){
            var arr = response.data;
            var arrsplit = arr.split(',');
        });
    }
});

I want to access the arrsplit variable in the script tag in the keymetric.template.html file

Ad

Answer

Use $rootScope.

$http.get('customers.csv').then(function(response){
            var arr = response.data;
            var arrsplit = arr.split(',');
            $rootScope.datareceived = arrsplit;
        });

Now in html

access like {{$root.datareceived[0]}} .

To access scope variable in script

angular.element(document.querySelector('[ng-controller="controllername"]')).scope().yourscopevariable

or by using jquery

var whateveryouwant = $('[ng-controller="controllername"]').scope().yourscopevariable;

Here is a generic way to get hold of scope variable outside angular context

function getScope(ctrlName) {
    var sel = 'div[ng-controller="' + ctrlName + '"]';
    return angular.element(sel).scope();
}

This can be called by passing the controller name

var $scope = getScope('ctrl');
Ad
source: stackoverflow.com
Ad