Reputation: 23
I have Angularjs variable that I want to pass in javascript variable. I found solution here so it didn't work. My code :
<script>
var demo=angular.module('demo', []);
demo.controller('metrics', function($scope, $http) {
$http.get('http://localhost:8080/metrics').then(function(response)
{
$scope.metrics = response.data;
});
});
</script>
<div ng-controller="metrics">
<p>{{metrics}}<p>
</div>
<script>
var e = angular.element(document.querySelector('[ng-controller="metrics"]'));
var e1 = e.scope().metrics ;
alert(e1)
</script>
I got result from {{metrics}} but e1 didn't return something.
Thanks for your help.
Upvotes: 1
Views: 3184
Reputation: 241
angular.element() is a function in angular to get a raw DOM
if you want to get a particular <p>
then assign id attribute on it
with that raw DOM, you can add attribute, add classes or else (check this link for more info)
but if you want to do something with metrics
then just use $scope.metrics
after you get it from $http
<div ng-controller="metricsCtrl">
<p id="metric">{{metrics}}<p>
</div>
<script>
var demo=angular.module('demo', []);
demo.controller('metricsCtrl', function($scope, $http) {
$http.get('http://localhost:8080/metrics').then(function(response)
{
$scope.metrics = response.data;
// you can do whatever with $scope.metrics here
console.log($scope.metrics);
});
var e = angular.element(document.querySelector('#metric'));
console.log(e);
e.addClass('some-class'); // here p will be <p class="some-class" id="metric">{{metrics}}<p>
});
</script>
Upvotes: 1
Reputation: 18657
From your current code, by the time the JS
code executes, it will not contain metrics
data.
The JS
code should be written in the then
response of the API call,
If you do that, the JS
code will be called after the metrics
gets a value.
var demo=angular.module('demo', []);
demo.controller('metrics', function($scope, $http) {
$http.get('http://localhost:8080/metrics').then(function(response)
{
$scope.metrics = response.data;
var e = angular.element(document.querySelector('[ng-controller="metrics"]'));
var e1 = e.scope().metrics ;
alert(e1);
});
});
Upvotes: 1