2012-10-12 292 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}}')中使用雙向綁定 –