2012-10-12 208 views
5

我正在用模态窗口构建一个AngularJS web应用程序。在模式窗口中,我可以显示一个JQuery Flot实时图,与此类似: http://people.iola.dk/olau/flot/examples/realtime.html如何将AngularJS变量传递给Javascript?

我的网站显示多个用户,但用户数量可能因所选内容而异。我喜欢为每个用户显示一张图表。这是我难过的地方。

我从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); 
… 

我AngularJS web应用程序有这样的代码:

在index.app.html:

<!DOCTYPE HTML> 
<html ng-app="app"> 
... 
<body ng-controller="AppCtrl"> 
... 
<div class="container"> 
    <div ng-view></div> 
</div> 
... 

在模板(的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> 
... 

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

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

回答

0

是的,这是一个棘手的问题想想,我们习惯于模板。因为我们并不是真的应该从控制器做过多的DOM操作,你可能会想创建一个指示,here's an example.

测试HTML:

<body ng-controller="MainCtrl"> 
    UserId: {{userId}}<br/> 
    <my-flot-chart ng-model="name"></my-flot-chart> 
</body> 

这里的示例代码。

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); 
    } 
    } 
}) 
+0

@blesh喜: 我已经在我的index.app.html文件中的BODY标签。我不认为我可以将另一个BODY标签放入我的index.html(模板)文件中,我可以吗?我的模板文件以HEADER标签开头。 userId的值在我的index.html(模板)文件中。 ng-repeat会创建多行用户,每个用户都有自己的userId。我没有看到如何传递给Javascript代码。我假设你建议我忘记将{{userId}}中的值传递给HTML文件中的Javascript代码? AngularJS有多个JS文件。我应该把你的代码放到哪个JS文件中? – Curt

1

我喜欢用指令blesh的建议,但建议的处理方式稍有不同(对不起,我没有现在的带宽)。对于你有的代码,我认为你需要的只是一个小小的调整。

<td ng-click="href('#/profile/{{user.user_ID}}')" data-dismiss="modal">{{user.user_name}}</td> 

的指令封装是一个更好的解决方案,但是,如果你的枪下,需要看到那么它的工作,我认为这是确定 - 现在。让我知道这是否适合你。

--Dan

+0

我对Blesh提出了如何创建该指令的问题,因为我没有看到如何创建该指令。抱歉在AngularJS指令中成为新手。您使用ng-click对一行代码进行了评论,这不是我需要帮助的地方,所以我可能不应该在我的发布中包含该代码。你建议的小调整是什么? – Curt

+0

抱歉没有真正回答你的问题。我会在本周晚些时候看看我是否记得把一些代码挖掘出来。小调整是在ng-click href('#/ profile/{{user.user_ID}}')中使用双向绑定 –