如何在JavaScript函数中包含AngularJS变量?

时间:2013-10-07 10:16:45

标签: javascript function angularjs

我需要遍历JSON文件,我正在使用AngularJS。功能如下:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script>
        function PostsCtrlAjax($scope, $http) {
        $http({method: 'POST', url: 'posts.json'}).success(function(data) {
                $scope.tasks = data;
            });
        }
</script>
<div id="ng-app" ng-app ng-controller="PostsCtrlAjax"> 
        <div ng-repeat="task in tasks.objects">
<script type="text/javascript">     
var adviser1 = new primitives.orgdiagram.ItemConfig("{{task.name}}", "{{task.description}}", "http://www.basicprimitives.com/demo/images/photos/z.png");
</script>
</div>
</div>

通过使用以下代码{{task.name}}并将描述打印为{{task.name}},如何打印出该变量的内容?如果我没有使用引号,它就不会显示任何内容。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

我认为您需要检查您的代码设计。在<script>中使用ng-repeat标记的想法对我来说并不是最佳做法。

您可以创建可以放在directive内的简单ng-repeat。每次循环实例化其中一个指令时,您可以使用所需的所有参数运行函数new primitives.orgdiagram.ItemConfig()

我创建了类似的东西,但我没有调用你的函数,而是在控制台上打印。

请查看下面的代码或此处的工作示例(http://plnkr.co/edit/1J2Ep6DbfUiFDkL6TUAv?p=preview

 <!doctype html>
  <html lang="en" ng-app="myApp">
  <head>
   <meta charset="UTF-8">
    <title>Document</title>
     <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
     <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>

      <script>

       var myApp = angular.module('myApp', []);

       myApp.controller('PostsCtrlAjax', ['$scope', '$http' ,function ($scope, $http) {

       $scope.tasks = {
        "data" :  [ 
         {
          name: 'Task 01',
          description: 'Task 01 Description',
          url: 'http://www.basicprimitives.com/demo/images/photos/z.png'
         },
        {
          name: 'Task 02',
          description: 'Task 02 Description',
          url: 'http://www.basicprimitives.com/demo/images/photos/z.png'
        }
      ]
    };
  }]);


  myApp.directive('adviser', [ '$compile', function ($compile) {
    return {
     restrict: 'A',
     transclude: true,
     replace: true,
      scope: {
       item : "="
      },
     link: function (scope, element, iAttrs) {

         var template = '<button ng-click="createAdviser(item.name, item.description, item.url)">{{item.name}}</button>';


         scope.createAdviser = function(name, description, url) {

         // var adviser1 =  new primitives.orgdiagram.ItemConfig(name, description, url);

            var adviser =  [name, description, url];

            console.log(adviser)

         }

         element.html(template).show();

         $compile(element.contents())(scope);

       }
     };
   }])

  </script>

  </head>
 <body>


 <div ng-controller="PostsCtrlAjax"> 
   <div ng-repeat="task in tasks.data">
     <div adviser item="task"></div>
  </div>
 </div>

 </body>
 </html>