Note that there are some explanatory texts on larger screens.

plurals
  1. POAngularJS Passing Variable to Directive
    primarykey
    data
    text
    <p>I'm new to angularjs and am writing my first directive. I've got half the way there but am struggling figuring out how to pass some variables to a directive.</p> <p>My directive:</p> <pre><code>app.directive('chart', function () { return{ restrict: 'E', link: function (scope, elem, attrs) { var chart = null; var opts = {}; alert(scope[attrs.chartoptions]); var data = scope[attrs.ngModel]; scope.$watch(attrs.ngModel, function (v) { if (!chart) { chart = $.plot(elem, v, opts); elem.show(); } else { chart.setData(v); chart.setupGrid(); chart.draw(); } }); } }; }); </code></pre> <p>My controller:</p> <pre><code>function AdListCtrl($scope, $http, $rootScope, $compile, $routeParams, AlertboxAPI) { //grabing ad stats $http.get("/ads/stats/").success(function (data) { $scope.exports = data.ads; if ($scope.exports &gt; 0) { $scope.show_export = true; } else { $scope.show_export = false; } //loop over the data var chart_data = [] var chart_data_ticks = [] for (var i = 0; i &lt; data.recent_ads.length; i++) { chart_data.push([0, data.recent_ads[i].ads]); chart_data_ticks.push(data.recent_ads[i].start); } //setup the chart $scope.data = [{data: chart_data,lines: {show: true, fill: true}}]; $scope.chart_options = {xaxis: {ticks: [chart_data_ticks]}}; }); } </code></pre> <p>My Html:</p> <pre><code>&lt;div class='row-fluid' ng-controller="AdListCtrl"&gt; &lt;div class='span12' style='height:400px;'&gt; &lt;chart ng-model='data' style='width:400px;height:300px;display:none;' chartoptions="chart_options"&gt;&lt;/chart&gt; {[{ chart_options }]} &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I can access the <code>$scope.data</code> in the directive, but I can't seem to access the <code>$scope.chart_options</code> data.. It's definelty being set as If I echo it, it displays on the page..</p> <p>Any ideas what I'm doing wrong?</p> <p><strong>UPDATE:</strong> For some reason, with this directive, if I move the <code>alert(scope[attrs.chartoptions]);</code> to inside the $watch, it first alerts as "undefined", then again as the proper value, otherwise it's always undefined. Could it be related to the jquery flot library I'm using to draw the chart?</p> <p>Cheers, Ben</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload