简体   繁体   中英

Not getting data in AngularJS Directive from the $scope model

Am working on a webpage using AngularJS. On the webpage I am displaying charts using Chartist.js. I want to populate the data needed by the Chartist chart object with a call to a REST service returning JSON data and feeding this to the Chartist chart data model. The webpage just displays the chart inside a panel. I had a Angular controller that called the REST service, got the data and then I assigned this data to a $scope model. I wanted to pass this model data to the Chartist object. For this I had a directive applied to an element and passing the model data as an attribute value and in the directive, got this data, created a Chartist object and passed this model data. However the chart is not being displayed indicating that no/null data was passed to the Chartist object. What am I doing wrong here! ?... Here is the html file

    <!DOCTYPE html>
<html ng-app="codeQualityApp">
<head>
<title>First Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="lib/angularjs/angular.js"></script>
<!--<script src="controllers/client.controller.codequality.js"></script>-->
<link href="css/bootstrap.css" rel="stylesheet" />
<link href="css/bootstrap-theme.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet" />
<script>
  angular.module("codeQualityApp",[])
  .controller('codeQualityCtrl',function($scope,$http)
  {
    $scope.violationsData = {}; // Model data in the format below as needed by the Chartist object
   // $scope.violationsData.labels = ["Clang","MySQL","JDK 8"];
    //$scope.violationsData.series= [[369492,167703,159215]];

    $http.get("http://localhost:5001rest/codequality/list") // REST call
    .success(function(data,status,header,config)
    {
      var cq_violations = angular.fromJson(data);
      violationsData = {};
      violationsData.labels = new Array();
      violationsData.series = new Array(); 
      violationsData.series[0] = new Array();
      for(var i =0; i < cq_violations.length; i++)
      {
        violationsData.labels[i] = cq_violations[i].name;
        violationsData.series[0][i] = parseInt(cq_violations[i].msr[0].val,10);
      }
      $scope.violationsData = violationsData; // Populating the model data
    })
    .error(function(data,status,header,config)
    {
      $scope.error = data;
    });
    })
    .directive("cqChart",function()
    {
      return function(scope,element,attrs)
        {
           chartdata = scope[attrs["chartdata"]]; // Accessing the attribute value
          console.log("ChartData:",chartdata); // Am getting empty object here!!!
          new Chartist.Bar('.ct-chart', chartdata); // Bar chart with the data as in chartdata 
                                                                                 // but chart not displayed as chartdata is empty
                                                                                 // object!!
        }
    });


</script>
</head>

<body ng-controller="codeQualityCtrl"> // Controller
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Dashboard</a>
    </div>
    <div>
      <ul class="nav navbar-nav">
        <li><a href="master.html">Master</a></li>      
        <li><a href="#">Project/Features</a></li>
        <li><a href="build.html">Build</a></li>
        <li class="active"><a href="#">Code Quality</a></li>
        <li><a href="#">Test Execution</a></li>
        <li><a href="#">Deployments</a></li>

      </ul>
    </div>
  </div>
</nav>

<div class="alert alert-danger" ng-show="error">
Error ({{error}}). CodeQuality data was not loaded.
<a href="/app.html" class="alert-link">Click here to try again</a>
</div>

<div class="panel panel-default" ng-hide="error"> 
  Data : {{violationsData}} <!-- Got proper data here -->
<!-- Display the chart here -->
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<div class="ct-chart ct-perfect-fourth"></div>
<cq-chart chartdata="violationsData"> <!-- custom directive ... not working... data is empty -->
</div>

</body>
</html>

The way you are accessing the value, you always get the initialized value not updated You find it empty because that was the initial value $scope.violationsData = {}; your value is updated after ajax success. The updated value will not propagated to your directive. So to get updated value you can $watch or pass the value using = like

.directive("cqChart", function () {
    return {
        restrict: 'E',
        scope: {
            // this will create isolate scope and two way bind between
            // your controller's violationsData and directive's chartdata
            chartdata: '=' 
        },
        link: function (scope, element, attrs) {
            //now this will be accessable through scope
            console.log("ChartData:", scope.chartdata); 
        }
    }
});

Note - Don't use something = someValue; use var like var something = someValue otherwise this will create global variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM