【问题标题】:passing complex data to ng-directive将复杂数据传递给 ng-directive
【发布时间】:2017-02-05 02:55:40
【问题描述】:

我正在尝试在 Angular 中构建自定义指令;它需要在渲染页面之前对传递给它的数据进行处理,因此我需要通过属性获取传递给我的指令的数据并做一些事情,最后渲染页面。

.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 函数中

【问题讨论】:

  • 您使用的是什么版本的 Angular?有几种方法可以定义自定义标签,我想根据你的版本来回答。
  • 我正在使用 Angular 1.6.1 @MichaelKucinski
  • 更新了我的答案

标签: javascript angularjs


【解决方案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>

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

【讨论】:

【解决方案2】:

对于 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>

【讨论】:

    猜你喜欢
    • 2013-09-27
    • 2014-04-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多