将复杂数据传递给ng-directive

时间:2017-02-04 16:35:27

标签: javascript angularjs

我试图以角度构建自定义指令;它需要在渲染页面之前传递给它的rielaborate数据,所以我需要通过属性将数据传递给我的指令并做一些事情,最后渲染页面。

.directive('lpcEdiTable', function($interpolate) {
        return {
            restrict: "E",
            templateUrl: "...",
            replace: false,
            scope: {
                collection: "="
            },
            link: function(scope, elem, attr) {
                //here i need to retrieve data
                var myColl = scope.collection; //it's not working
                //do some stuff here on myColl
                scope.collection = myColl;
            }
        };
    });

所以我在这里使用指令:

<lpc-edi-table collection="products"></lpc-edi-table>

其中products是一个复杂的对象。

在指令模板中,我将后精化数据用于ng-repeat和其他东西

我试图关注this,但我无法将数据检索到link函数

2 个答案:

答案 0 :(得分:1)

以下是将对象传递给指令

的示例
angular.module("myModule", [])
.controller("baseController", ['$scope', function($scope) {
  $scope.products = [
        "asd", 
        "asdasd"
    ];
}])

.directive('myDirective', function() {
  return {
    restrict: "E",
    template: "<p ng-repeat='item in collection'>{{item.attr}}</p>",
    scope: {
      collection: "="
    },
    link: function(scope, elem, attr) {
      if (!attr.collection) throw new Error("lpc-edi-table directive: 'collection' attribute not found!");
      scope.collection = scope.collection.map(function(a) { return {attr: a} });

      console.log(scope.collection);


    }
  };
});

您可以像

一样调用您的指令
<my-directive collection="products"></my-directive>

DEMO https://plnkr.co/edit/cj4oSPRiNo8iYfinIztT?p=preview

答案 1 :(得分:0)

对于Angular 1.6,我建议using components。特别是如果你不需要进行高级DOM操作。

app.component('lpcEdiTable', {
    // $ctrl is controller instance
    template: '<div ng-repeat="object in collection">{{object | json}}</div>',
     bindings: { //custom attributes
         collection: '<' //one way binding. Can also be two way =
     },
     controller: function(){
         //$onInit gets called when the bindings are ready
         this.$onInit = function(){
             // this.collection is now ready
             // safe to manipulate
         };
      }
});

这可以像:

一样使用
<lpc-edi-table collection="products"></lpc-edi-table>