Сделайте так, чтобы каждый новый элемент, созданный в списке (каждый с другим идентификатором), автоматически выполнял определенную функцию - PullRequest
0 голосов
/ 27 января 2019

Я объясняю себе: у меня есть пользовательский список Sharepoint, и я использую AngularJS для вызова этого списка. На основании данных, которые я получаю из списка, я делаю «одну гистограмму» для каждого элемента в этом списке. Я использую jquery.lineProgressbar.js для построения графиков.

Я делаю таблицу с ng-repeat . И мне нужно предоставить разные имена ID для каждого "div диаграммы", иначе jquery.lineProgressbar.js не будет работать. Вот мой HTML:

<table>
  <tr>
    <td>Name</td>
    <td>Productivity percentage</td>
  </tr>
  <tr ng-repeat="item in items">
    <td>{{item.Name}}</td>
    <td>
       <!-- The "ng-attr-id" provides the div a different ID depending the name they introduce. i.e.: "chart-Person1" -->
       <div ng-attr-id="{{'chart-' + item.Name}}" data-percentage="{{item.Productivity_x0020_percentage}}"></div>
    </td>
  </tr>
</table>

и моя главная проблема, ПИСЬМО:

<script>
  //I need to call each chart, one by one like this:
  chartFunction('chart-Person1');
  chartFunction('chart-Person2');
  chartFunction('chart-Person3');
  chartFunction('chart-Person4');
  //and I need to make this automatically,
  //because people will submit new items whenever they want,
  //and I can't be updating the script each time someone uploads something.

  function chartFunction(elementID) {
    var dataPercentage = $("#" + elementID).data('percentage');
    //this calls the chart code
    $("#" + elementID).LineProgressbar({
      //it says that the div selected will have a "percentage" equals to the percentage they wrote in the list.
      percentage: dataPercentage
    });
  }
</script>

У меня есть Плункер. Он немного отличается тем, что имеет функцию, которая запускает диаграммы только тогда, когда они находятся в области просмотра, и не использует AngularJS. Но это только для того, чтобы вы могли увидеть, как это работает: мой Плункер

Итак, как я сказал в своем коде, мне нужно вызывать каждый новый элемент, добавляемый в список sharepoint, но я не могу создавать новые вызовы в моем коде каждый раз, когда кто-то загружает элемент. Заранее спасибо за помощь.

1 Ответ

0 голосов
/ 28 января 2019

Я нашел решение для этого.
Мне нужно было сделать это непосредственно при вызове списка (в угловом коде).

    <script>
    var myApp = angular
    .module('myApp', [])
    .controller('myController', function ($scope, $http) {

        //first I call the Sharepoint List with AngularJS
        $http({
            method: 'GET',
            url: "SiteURL/_api/web/lists/getByTitle('Employees List')/items?$select=*",
            headers: { "Accept": "application/json;odata=verbose" }
        }).then(function onSuccess(response) {
            //If the call is successful I create an empty Array called "peopleArray"
            //Here I will store the names of the divs which will run the chart's code
            $scope.items = response.data.d.results;
            var theItems = $scope.items,
                peopleArray = [];

            //I run a loop to go through all the items in the Sharepoint list
            //I assign a name for each person in the "peopleArray"
            for(var i=0; i<theItems.length; i++) {
                var currentItem = theItems[i];
                peopleArray.push('chart-' + currentItem.Name);
            };

            //I run another loop, this one goes through the "peopleArray"
            //each item executes the function below with the div name assigned in the previous loop
            for(var z=0; z<peopleArray.length; z++) {
                chartFunction(peopleArray[z]);
            }

            //and this is the function to make the charts for each person
            function chartFunction(elementID) {
                var dataPercentage = $("#" + elementID).data('percentage');
                $("#" + elementID).LineProgressbar({
                    percentage:dataPercentage
                });
            }
         }).catch(function onError(response) {
            //In case of Error, it will pop an alert
            alert("Error! The charts can't be loaded.");
        });
    });
    </script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...