将对象的键传递给指令

时间:2017-03-24 20:29:05

标签: angularjs angularjs-directive

我已经创建了一个指令作为md-autocomplete的包装器,因此它更容易重用。在父控制器中,我有一个对象。我想将对象的键传递给我的自定义指令,但我遇到了麻烦。简化代码,没有md-autocomplete

这是脚本

var app = angular.module('myApp',[])
.controller('parentController', function(){
  var parent = this;
  parent.things = {item1: {color: "blue"}, item2: {color: "red"}};
})
.directive('childDirective',function(){
  return {
    scope: {},
    bindToController: {
       items:'&'
    },
    controller: childController,
    controllerAs: 'child',
    template: '<pre>{{child.items | JSON}}<pre>' //should be [item1,item1]
  }

  function childController(){
    //Just a dummy controller for now
  }
})

HTML

<div ng-app="myApp" ng-controller="parentController as parent">
    <my-directive items="Object.keys(parent.things)">
    </my-directive>
</div>

TL; DR:如何将父控制器中定义的对象的键传递给子指令?我需要传递密钥,而不是对象本身,因为我的指令旨在处理字符串数组。

2 个答案:

答案 0 :(得分:1)

尝试使用带有user attribute(=)

的局部作用域的指令
app.directive('childDirective', function() {
  return {
    replace: true,
    restrict: 'E',
    scope: {
         items: '='
    },
    template: '<pre>{{items | JSON}}<pre>'
  };
});

使用该指令,属性“items”中的对象“按原样”传递,作为范围变量“items”

<div ng-app="myApp" ng-controller="parentController as parent">
    <my-directive items="getKeys(parent.things)">
    </my-directive>
</div>

使用Object.keys(obj)作为源将导致无限循环摘要(该函数总是返回一个新的不同对象)。您需要一个函数将结果保存到本地可更新对象,如下例所示:

https://jsfiddle.net/FranIg/3ut4h5qm/3/

$scope.getKeys=function(obj){
  //initialize result
  this.result?this.result.length=0:this.result=[];
  //fill result
  var result=this.result;  
  Object.keys(obj).forEach(function(item){
   result.push(item);
   })
  return result;
}

答案 1 :(得分:0)

我认为@ Igor的答案是正确的,因为最终它把我带到了正确的地方。但是,我想提供我的最终解决方案,这对于评论来说太大了。

搜索这个问题的答案让我创建了一个更灵活的指令,可以采用几种不同类型的输入。

真正的密钥(以及我对原始问题的实际答案)是将items参数绑定到指令中的代理getter / setter对象。基本设置是:

app.directive('myDirective',function(){
  return {
    ...
      controller: localControl,
      bindToController: {
        items: '<' //note one-way binding
      }
    ...
  }
  function localControl(){
    var child = this;
    child._items = [],

    Object.defineProperties(child,{
       items: {
         get: function(){return child._items},
         set: function(x){child._items = Object.keys(x)}
       }
    });
  }
});

HTML

<my-directive items="parent.items">
  <!-- where parent.items is {item1:{}, item2:{}...} -->
</my-directive>

最终,我决定我希望我的指令能够接受各种格式,并提出this plunk作为演示。

请随时提供有关改进我的代码的意见/建议。谢谢!

相关问题