在 ng-include 中重命名变量 [英] renaming a variable in ng-include

查看:21
本文介绍了在 ng-include 中重命名变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是相关的html:

<ng-include src="'app/views/order.html'"></ng-include>

附加到这个 ng-include 嵌套的作用域是一个贸易变量.贸易变量看起来像:

Attached to the scope this ng-include is nested in is a trade variable. The trade variable looks like:

var trade = {
    order: {}
}

问题是 order.html 需要一个订单变量而不是 trade.order

The problem is that order.html is expecting an order variable not a trade.order

如何调用 ng-include 并将 trade.order 作为 order 传入?

How can I call the ng-include and pass in trade.order as order?

推荐答案

ng-include 读取全局范围内的变量.你不能用那个.它不会工作.

ng-include reads the variables within the global scope. You cannot use that. It won't work.

并且不要使用onload,因为它会影响全局范围.

And do not use onload because it litters the global scope.

更清洁的解决方案是使 一个新的通用指令

The cleaner solution is to make a new generic directive

这是理想的用法:

<div ng-include-template="'app/views/order.html'" ng-include-variables="{ order: trade.order }"></div>

指令是:

.directive(
  'ngIncludeTemplate'
  () ->
    {
      templateUrl: (elem, attrs) -> attrs.ngIncludeTemplate
      restrict: 'A'
      scope: {
        'ngIncludeVariables': '&'
      }
      link: (scope, elem, attrs) ->
        vars = scope.ngIncludeVariables()
        for key, value of vars
          scope[key] = value
    }
)

您可以看到该指令没有使用全局作用域.相反,它从 ng-include-variables 读取对象并将这些成员添加到其自己的本地范围.

You can see that the directive doesn't use the global scope. Instead, it reads the object from ng-include-variables and add those members to its own local scope.

我希望这会有所帮助.它干净而通用.

I hope this helps. It's clean and generic.

这篇关于在 ng-include 中重命名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆