【问题标题】:How to access angular scope variable in JavaScript file如何访问 JavaScript 文件中的角度范围变量
【发布时间】:2015-06-07 00:20:57
【问题描述】:

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

我定义了一个角度服务和控制器。

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}},
            }]
        }));

【问题讨论】:

  • 在您使用 highcharts 时告诉我一件事?是在窗口对象中设置数据之后还是之前?这里的执行顺序很重要。
  • Highcharts 是在数据设置好后渲染的。
  • 您可以熟悉prepared 指令,这似乎更易于使用。 See reference

标签: javascript jquery angularjs highcharts


【解决方案1】:

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

<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()

【讨论】:

  • 这应该可以,但是当图表加载时,范围为空或为空。
  • 你到底想做什么??
  • 你在说哪个范围我没听懂??
【解决方案2】:

您需要将图表放在指令中。从指令中,您将能够访问范围。

【讨论】:

  • 我不明白如何使用指令将变量传递给给定的模板,你能解释一下吗?
  • 你可以将你的指令绑定到一个控制器,然后它就会正常工作。 “将变量传递给给定的模板”是什么意思?
猜你喜欢
  • 1970-01-01
  • 2016-06-06
  • 2017-08-03
  • 2023-04-07
  • 1970-01-01
  • 2012-06-17
  • 2010-11-16
  • 2015-08-21
  • 1970-01-01
相关资源
最近更新 更多