Angularjs-需要在点击元素时编译模板

时间:2015-12-14 05:06:25

标签: javascript html angularjs

我在angularjs中创建一个复杂的表;点击->order('ai.sort_order ASC');我需要进行ajax调用并填充我点击的行下新行中的所有值。
到目前为止,我已经实现了这个目标

<td>
var app1 = angular.module('reportModule', []);
app1.directive('tableValue', function($q, $http, $templateCache) {

  return {
    restrict: 'A',
    template: '<tr><td id="greenBackground">{{result.project}}</td><td>{{result.val1}}</td><td>{{result.val2}}</td><td>{{result.val3}}</td><td>{{result.val4}}</td><td>{{result.val5}}</td><td id="greenBackground"></td><td id="greenBackground"></td><td id="greenBackground"></td><td id="greenBackground"></td></tr>',
    link: function(scope, elm, attrs) {
      scope.clickme = function() {
        var dataToSend = elm.text();
        console.log(attrs);
        $http({
          method: 'GET',
          params: {
            'portfolio': dataToSend
          },
          url: 'getProjectforCOQ.do',
          cache: true
        }).then(function(result) {
          $compile(template)(scope);
        });
      };


    }
  };


});

点击完成后,我完全迷失了编译模板的麻烦。需要帮助。

1 个答案:

答案 0 :(得分:1)

我希望这可以帮助你:)。

&#13;
&#13;
<!DOCTYPE html>
<html ng-app="reportModule">

<head>
  <title>stackoverflow</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
</head>

<body>

  <table-value></table-value>

  <script>
    var app = angular.module('reportModule', []);
    app.directive('tableValue', function($q, $http) {

      return {
        restrict: 'E',
        template: '<button ng-click="clickToCallAjax()">load data</button><table><tr ng-repeat="info in infos"><td ng-bind="info.val"></td><td ng-bind="info.val2"></td><td ng-bind="info.val3"></td></tr></table>',
        link: function(scope, elm, attrs) {

          //this is my current data
          scope.infos = [{
            val: "val1",
            val2: "val2",
            val3: "val3"
          }, {
            val: "val4",
            val2: "val5",
            val3: "val6"
          }];

          scope.clickToCallAjax = function() {
            //call your ajax and fill the infos
            //response is your ajax answer
            var response = [{
              val: "val7",
              val2: "val8",
              val3: "val9"
            }, {
              val: "val10",
              val2: "val1",
              val3: "val2"
            }];

            //scope.infos = response [if you want to remove old data and replace them]

            //[if you want to push new data in your table]
            angular.forEach(response, function(item) {
              scope.infos.push(item);
            });
          };
        }
      };
    });
  </script>
</body>

</html>
&#13;
&#13;
&#13;