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

Not getting data in AngularJS Directive from the $scope model

本文关键字:指令 数据 AngularJS 获取 scope 模型 未从      更新时间:2023-09-26

我正在使用AngularJS开发网页。在网页上,我使用Chartist.js显示图表。我想通过调用REST服务来填充Chartist图表对象所需的数据,该服务返回JSON数据并将其提供给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>

访问值的方式总是得到初始化的值而不是更新您发现它是空的,因为这是初始值$scope.violationsData = {};您的值在ajax成功后更新。更新后的值不会传播到您的指令。因此,要获得更新的值,您可以使用$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); 
        }
    }
});

注意-不要像var something = someValue那样使用something = someValue;使用var,否则将创建全局变量。