简体   繁体   English

使用服务时AngularJS无法正确加载指令

[英]AngularJS not loading directive correctly when using services

I am new to JavaScript and working on something where I retrieve data from MongoDB and writing code on AngularJS to draw a pie chart using Highcharts . 我是JavaScript的新手,从事的工作包括从MongoDB检索数据并在AngularJS上编写代码以使用Highcharts绘制饼图。 Code works fine when I am using just Angular controller without service but doesn't work when use service in between even though I hard code data in service. 当我仅使用不带服务的Angular控制器时,代码可以正常工作,但是即使我在服务中对数据进行硬编码,也无法在两者之间使用服务时使用代码。 I am giving here working code and non-working code as well. 我在这里也提供了工作代码和非工作代码。 I need to make this working using services as I need to read the actual data from MongoDB. 我需要使用服务来使其工作,因为我需要从MongoDB中读取实际数据。

Below is my HTML file and JavaScript code for controller, service, etc. I have even hardcoded response that I am getting from service into controller to make sure it has data the way it is expected but still it is not drawing chart as expected. 下面是我用于控制器,服务等的HTML文件和JavaScript代码。我什至对从服务到控制器的响应进行了硬编码,以确保它具有预期的数据,但仍未按预期绘制图表。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
<script src="js/controllers/twittersentimentcontroller.js"></script>
<script src="js/services/twittersentimentservice.js"></script>
<script src="js/core.js"></script>


<div ng-app="myApp">
  <div ng-controller="mainController">
    <div class="hc-pie" items="limitedIdeas"></div>
    <div items="limitedIdeas">{{limitedIdeas}}</div>
  </div>
</div>

Controller, directive, services code is as below. 控制器,指令,服务代码如下。

angular.module('myController', [])

    // inject the Todo service factory into our controller
    .controller('mainController', ['$scope','$http','some', function($scope, $http, some) {
        $scope.loading = true;
        console.log("inside controller...............");    

        some.get("android")
            .then(function(data) {
                console.log(data);
                $scope.sentiments = [["Positive", 26], ["Negative", 5], ["Nutral", 69]];
                $scope.ideas = [["Positive",2],["Negative",5],["Nutral",69]];
                $scope.limitedIdeas = [["Positive",2],["Negative",5],["Nutral",69]];
                $scope.loading = false;
            });    
    }]);

angular.module('myApp')
  .directive('hcPie', function () {
  return {
    restrict: 'C',
    replace: true,
    scope: {
      items: '='
    },
    controller: function ($scope, $element, $attrs) {
      console.log(2);

    },
    template: '<div id="container" style="margin: 0 auto">not working....Please work....</div>',
    link: function (scope, element, attrs) {
      console.log(3);
      var chart = new Highcharts.Chart({
        chart: {
          renderTo: 'container',
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false
        },
        title: {
          text: 'Browser market shares at a specific website, 2010'
        },
        tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage}%</b>',
          percentageDecimals: 1
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
              enabled: true,
              color: '#000000',
              connectorColor: '#000000',
              formatter: function () {
                return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
              }
            }
          }
        },
        series: [{
          type: 'pie',
          name: 'Browser share',
          data: scope.items
        }]
      });
      scope.$watch("items", function (newValue) {
        chart.series[0].setData(newValue, true);
      }, true);

    }
  }
});

Services: 服务:

angular.module('someService', [])

    // super simple service
    // each function returns a promise object 
    .factory('some', ['$http',function($http) {
        return {
            get : function(instrument) {
                return $http.get('/api/sent/'+instrument);
            }
        }
    }]);

Below is the code how we connect controller, service together. 以下是我们如何将控制器和服务连接在一起的代码。

angular.module('myApp', ['myController', 'someService']);

Web page does display [["Positive",2],["Negative",5],["Nutral",69]] value when I try to display them so hard coded value on controller is there on scope but for some reason my directive is not loading correctly. 当我尝试显示网页时,网页确实显示[["Positive",2],["Negative",5],["Nutral",69]]值,因此在控制器上存在硬编码值,但出于某种原因我的指令未正确加载。

If I do below code directly without service or something, it works fine and it does draw entire pie-chart as expected but why it doesn't work when I use the same thing via services. 如果我直接在不使用服务或其他方法的情况下执行以下代码,则它可以正常工作,并且确实可以按预期绘制整个饼图,但是当我通过服务使用同一事物时,为什么它不起作用。 As I mentioned, my service does work correctly and I see that it gets me exact that data I am expecting in the expected format as well (I have hard coded same thing here). 正如我所提到的,我的服务确实可以正常工作,并且我可以准确地以期望的格式获得我所期望的数据(我在此处进行了硬编码)。

Please check below code which works fine and draws the pie chart alright but not above code using service doesn't work. 请检查下面的代码,该代码工作正常并可以绘制饼图,但上面的代码使用service无效。 Can you help what is wrong with above code? 您能协助上述程式码出什么问题吗?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <div class="hc-pie" items="limitedIdeas"></div>
  </div>
</div>

<script>
function MyCtrl($scope, limitToFilter) {
  $scope.ideas = [
    ['ideas1', 1],
    ['ideas2', 8],
    ['ideas3', 5]
  ];

  $scope.limitedIdeas = limitToFilter($scope.ideas, 3);
}

angular.module('myApp', [])
  .directive('hcPie', function () {
  return {
    restrict: 'C',
    replace: true,
    scope: {
      items: '='
    },
    controller: function ($scope, $element, $attrs) {
      console.log(2);

    },
    template: '<div id="container" style="margin: 0 auto">not working</div>',
    link: function (scope, element, attrs) {
      console.log(3);
      var chart = new Highcharts.Chart({
        chart: {
          renderTo: 'container',
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false
        },
        title: {
          text: 'Browser market shares at a specific website, 2010'
        },
        tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage}%</b>',
          percentageDecimals: 1
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
              enabled: true,
              color: '#000000',
              connectorColor: '#000000',
              formatter: function () {
                return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
              }
            }
          }
        },
        series: [{
          type: 'pie',
          name: 'Browser share',
          data: scope.items
        }]
      });
      scope.$watch("items", function (newValue) {
        chart.series[0].setData(newValue, true);
      }, true);

    }
  }
});

</script>

be careful, angular.module('myApp', []) is a setter, and you use it two times, you should use it to instantiate your app, but use angular.module('myApp') after for a getter 请注意, angular.module('myApp', [])是一个setter,并且使用了两次,应该使用它来实例化您的应用程序,但是在使用getter之后再使用angular.module('myApp')

Could you also change '.success' by '.then' please. 您能否也将“ .success”更改为“ .then”。 .then use the promise system 。然后使用承诺系统

you wrote 'instr' instead of 'instrument', can you change it ? 您写的是“ instr”而不是“ instrument”,可以更改吗?

 .factory('some', ['$http',function($http) {
    return {
        get : function(instrument) {
            return $http.get('/api/sent/'+instrument);
        }
    }
}]);  

I changed some little things in your plunker and it works for me, if you dont have the data you want, you should watch in your back-end side http://plnkr.co/edit/ZShnouXLEVNxD1NHdev2?p=preview 我更改了您的插拔器中的一些小东西,它对我有用,如果您没有想要的数据,则应该在后端查看http://plnkr.co/edit/ZShnouXLEVNxD1NHdev2?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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