如何将AngularJS变量传递给Javascript?

Cur*_*urt 5 javascript bind flot angularjs

我正在构建一个带模态窗口的AngularJS Web应用程序.在模态窗口中,我可以显示一个JQuery Flot实时图表,类似于:http://people.iola.dk/olau/flot/examples/realtime.html  

我的网站显示多个用户,但根据所选内容,用户数可能会有所不同.我想为每个用户显示一个图表.这是我难倒的地方.

我从http://people.iola.dk/olau/flot/examples/realtime.html复制了Javascript代码并将其放在/js/flot/flot.user.js中,并进行了以下更改:

//$(function () {
function flotChart(user_ID) {
...
//var plot = $.plot($("#placeholder"), [ getRandomData() ], options);
var plot = $.plot($("#chart_" + user_ID), [ getRandomData() ], options);
…
Run Code Online (Sandbox Code Playgroud)

我的AngularJS网络应用程序有以下代码:

在index.app.html中:

<!DOCTYPE HTML>
<html ng-app="app">
...
<body ng-controller="AppCtrl">
...
<div class="container">
  <div ng-view></div>
</div>
...
Run Code Online (Sandbox Code Playgroud)

在模板(index.html)中:

...
<!--  Modal window -->
<script src="/js/flot/flot.user.js"></script>
<table class="table table-condensed">
  <tr ng-repeat="user in users">
    <td ng-click="href('#/profile/'+user.user_ID)" data-dismiss="modal">{{user.user_name}}</td>
    <td>
      <script type="text/javascript">
        flotChart({{user.user_ID}});
      </script>
      <div id="chart_{{user.user_ID}}" style="width:100%;height:150px;"></div>
    </td>
...
Run Code Online (Sandbox Code Playgroud)

我需要将{{user.user_ID}}传递给flotChart(user_ID),但如上所示,flotChart({{user.user_ID}})不起作用.

有人可以提出解决方案吗?

Ben*_*esh 0

是的,考虑到我们习惯模板的方式,这是一件棘手的事情。由于我们实际上不应该从控制器进行太多 DOM 操作,因此您可能需要创建一个指令,下面是一个示例。

测试html:

<body ng-controller="MainCtrl">
  UserId: {{userId}}<br/>
  <my-flot-chart ng-model="name"></my-flot-chart>
</body>
Run Code Online (Sandbox Code Playgroud)

这是示例代码。

app.controller('MainCtrl', function($scope) {
  $scope.userId = 123;
});

function flotChart(userId) {
  alert('passed: ' + userId);
}

app.directive('myFlotChart', function(){
  return {
    restrict: 'E',
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) {
      //create a new script tag and append it to the directive's element.
      var scr = document.createElement('script');
      var text = document.createTextNode('flotChart(' + scope.userId + ')');
      scr.appendChild(text);
      elem.append(scr);
    }
  }
})
Run Code Online (Sandbox Code Playgroud)