【问题标题】:Access ngModel's parent object inside directive link在指令链接中访问 ngModel 的父对象
【发布时间】:2015-02-04 10:57:32
【问题描述】:

在我的指令中要求 ngModel 并在我的链接函数中使用第四个参数 ngModel 后,我可以访问绑定模型的值。在我的例子中,这个绑定值是 product.id(在 ng-repeat 中)。

我现在如何从我的链接函数中读取我的产品对象的其他值?

<input type="hidden" ng-model="product.id" my-directive">

app.directive('myDirective', function() {
   restrict: "a",
   require: "ngModel",
   link: function(scope, element, attrs, ngModel) {
       // Here I want to read product.name, product.price etc
   }
});

【问题讨论】:

  • 我觉得您正在尝试做错事,甚至想要在绑定到<input type="hidden"> 的指令中使用此功能。你想达到什么目的?
  • 我必须为使用 AJAX 搜索产品的 select2 框设置默认值。即 id=product.id 和 text=product.name。
  • 那你为什么需要<input type="hidden">?默认值通过设置输入的vm模型来设置
  • 如果您想使用 AJAX 功能,您必须为 Select2 使用隐藏输入。由于您必须在 select2() 函数中设置 initialValue,这是唯一正确的方法。

标签: javascript angularjs angularjs-directive angularjs-scope


【解决方案1】:

您可以将产品与输入数据标签绑定; 喜欢:-

<input type="hidden" ng-model="product.id" data-product="product" my-directive">
app.directive('myDirective', function() {
   restrict: "a",
scope{
product: "=product"
},
link: function(scope, element, attrs, ngModel) {
       // Here I want to read product.name, product.price etc
       //Here scope.product will return all the values

   }
});

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 2018-05-27
    • 2013-04-24
    • 2016-08-07
    • 2017-06-24
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多