javascript - 如何访问 JavaScript 文件中的 Angular 范围变量

标签 javascript jquery angularjs highcharts

总的来说,我对 Angular 和 JavaScript 很陌生。我知道可能有一种简单的方法可以做到这一点,但我只是很难弄清楚。

我定义了一个 Angular 服务和 Controller 。

var app = angular.module('nodeAnalytics', []);

app.factory('myService', function($http) {
  var myService = {
    async: function() {
      // $http returns a promise, which has a then function, which also returns a promise
      var promise = $http.get('https://graph.facebook.com/lowes').then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});


app.controller('MainCtrl', [
'$scope', 'myService', '$window',
  function($scope, myService, $window){
    $scope.test = 'Hello world!';
     myService.async().then(function(d) {
      $scope.data = d.likes;
      $window.data = $scope.data;
      console.log($scope.data)
    });
}]);

我知道在我的html文件中我使用{{data}}来访问scope.data$window.data 允许我访问浏览器中的范围元素,但这并不是很有帮助,因为我不知道如何让 javascript 文件访问窗口元素。

如何访问 javascript/jquery 文件中的数据变量。

我正在使用 highcharts,我想将数据值放入图表参数中,但我不知道如何访问它。

  $('#container-rpm').highcharts(Highcharts.merge(gaugeOptions, {
            series: [{
                data: {{data}},
            }]
        }));

最佳答案

看看这个简单的代码你就会明白

<body ng-app="myApp" data-ng-controller="MainCtrl" id="div1">
  <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto">
  </div>
 <script>
  var app = angular.module('myApp', []);

  app.controller('MainCtrl', function($scope){

    $scope.d=[10, 20, 30, 40];

    });
  </script>
  <script>
$(function () {

  var scope = angular.element("#div1").scope();
    $('#container').highcharts({
        chart: {
            type: 'column'
        },
        title: {
            text: 'Column chart with negative values'
        },
        credits: {
            enabled: false
        },
        series: [{
        name: 'Bar Chart',
        data: scope.d

        }]
    });
});
</script>

</body>

您必须使用angular.element(#dom).scope()来访问$scope.d

如果您想在绘制图表之前更改array d的值,则必须使用$scope.$apply()

关于javascript - 如何访问 JavaScript 文件中的 Angular 范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30688825/

相关文章:

javascript - 使用 Paper.js 为正在绘制的圆制作动画

php - 在 PHP foreach 循环中使用 jQuery 函数

javascript - 传递字符串成为对象

json - 使用 angular 开发并模拟所有 json 请求/响应

javascript - 我在这里做的是糟糕的 Javascript 做法吗?

javascript - 如何获取 OpenLayers 3 的高程数据?

javascript - 在 Knockout JS 中访问普通 JS 数组内可观察值的值?

javascript - 为什么 jquery 代码在我的元素中不起作用

javascript - ng-repeat 工作错误 AngularJS

javascript - Angular 在注入(inject)的 cshtml 文件中,$compile 不起作用