【问题标题】:Angular directives two way binding with Object look upsAngular 指令与对象查找的两种方式绑定
【发布时间】:2016-01-14 23:45:11
【问题描述】:

我将两个绑定传递到自定义角度 v1.4.3 指令中。

  1. 一个具有 2way 绑定的对象(模型:'='),它可以是数组,也可以不是数组 [{something: 'foo'}, {something: 'moo'}, ...] 或只是 {something: 'foo ',其他:'测试'}
  2. 查找该模型以在该对象中使用(查找:'@')。它是描述在该指令中查找我想使用的数据的路径的字符串。例如“[0].something”或“.something”。

我已经创建了一个函数来使用字符串来获取数据,但它破坏了 2 路绑定,因为我对提取的数据所做的任何更新都与绑定的模型对象分开。

我用来查找带有字符串键的对象的函数是:

Object.resolve = function (path, obj, safe) {
  return path.split('.').reduce(function (prev, curr) {
    return !safe ? prev[curr] : (prev ? prev[curr] : undefined)
  }, obj || self)
}

vm.data = Object.resolve(vm.lookUp, vm.model); // finds the data I need to display and edit but breaks the binding to vm.model

是不是一种更角度的方式来做到这一点并保持绑定的完整性?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:
  1. 这种检索对象属性的功能已经实现 - $parse。
  2. 要维护绑定,请使用 $watch。
app.directive('test', function($parse) {
  return {
    restrict : 'E',
    scope : {
      model : '=',
      lookUp : '@'
    },
    template : 'Result is : {{result}}',
    link : function(scope, elem, attrs) {
      function getResult() {
        return $parse('model' + scope.lookUp)(scope);
      }  
      scope.$watch(getResult, function() {
        scope.result = getResult();
      });
    }
  }
})

http://plnkr.co/edit/J5vlnGkHfwNYDZHO4lx6?p=preview

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
相关资源
最近更新 更多