【问题标题】:how to pass an object to a directive template in angularjs?如何将对象传递给angularjs中的指令模板?
【发布时间】:2013-07-06 01:42:00
【问题描述】:

我正在尝试使用 ui-bootstrap 模态创建可重复使用的指令。

除了选项外,它几乎可以工作

这里是指令:

directive('update', function() {
return {
  restrict: "E", 
  templateUrl: "tplModal.html",
  scope: { 
    selected:"="
  },
  link: function(scope, elm, attr){
    scope.open = function (obj) {
      scope.shouldBeOpen = true;
    };

    scope.close = function () {
      scope.shouldBeOpen = false;
    };

    scope.opts = {
      backdropFade: true,
      dialogFade:true
    };
  }
}

})

和 tplModal.html

<button class='btn' ng-click='open(selected)'>Update</button>
    <div modal="shouldBeOpen" close="close()" options="opts">
        <div class="modal-header">
            <h3><i class="lead" icon="{{selected.type}}"></i> {{selected.name}}</h3>
        </div>
        <div class="modal-body">
            <!-- stuffs here -->
        </div>
        <div class="modal-footer">
            <button class="btn btn-warning cancel" ng-click="close()">Cancel</button>
        </div>
    </div>

尽管有scope.opts,但没有淡入淡出效果。

这是整个代码: http://plnkr.co/edit/Ab4BOH?p=preview

我做错了什么?

【问题讨论】:

  • 在这里发布代码,告诉你如何使用指令,告诉你期望代码做什么,以及它做什么。
  • 我更新了问题
  • 您的 plunk 不起作用,我收到“Plunk not found”错误。
  • 贴出tplModal.html的代码
  • 对不起。我更新了问题,plnkr 的链接正在运行

标签: angularjs angular-ui-bootstrap


【解决方案1】:

问题是你在post-linking function中添加opts属性到scope中,会在modal指令的linking函数之后调用,所以modal指令永远不会得到这些选项。

解决方法是将scope.opts = ...移到预链接功能:

directive('update', function() {
    return {
        ...
        compile: function() {
            return {
                pre: function(scope, elm, attr){
                    ...
                    scope.opts = {
                        backdropFade: true,
                        dialogFade: true
                    };
                }
            };
        }
    }
}

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

【讨论】:

  • 非常感谢!在过去的几个小时里,我一直在颠倒这个问题,但我离答案还很远。现在,如果我在 modal 中使用另一个组件(例如 ui-bootstrap datepicker 或 ngUpload),我应该将相关函数放在这个预链接函数中吗?
  • @desgnl 您可以,但您不必将函数放在预链接函数中,这实际上取决于何时调用您的函数。如果稍后会调用该函数,例如事件处理程序,则在链接后函数中定义它们是安全的。
猜你喜欢
  • 2013-01-15
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
相关资源
最近更新 更多