没有从$ scope模型获取AngularJS指令中的数据

时间:2015-11-05 10:06:19

标签: javascript angularjs angularjs-directive

正在使用AngularJS在网页上工作。在网页上,我使用Chartist.js显示图表。我想通过调用REST服务返回JSON数据并将其提供给Chartist图表数据模型来填充Chartist图表对象所需的数据。网页只显示面板内的图表。我有一个Angular控制器调用REST服务,获取数据,然后我将这些数据分配给$ scope模型。我想将此模型数据传递给Chartist对象。为此,我将一个指令应用于一个元素并将模型数据作为属性值传递,并在指令中获取此数据,创建一个Chartist对象并传递此模型数据。但是,未显示图表,表示没有/ null数据传递给Chartist对象。我在这做错了什么! ?...这是html文件

    <!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>

1 个答案:

答案 0 :(得分:-1)

您访问该值的方式,您始终会获得初始值未更新您会发现它为空,因为这是ajax成功后更新值的初始值$scope.violationsData = {};。更新后的值不会传播到您的指令。因此,为了获得更新的价值,您可以$watch使用=传递值,例如

.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); 
        }
    }
});

注意 - 请勿使用something = someValue;使用 var ,如var something = someValue,否则会创建全局变量。