renaming a variable in ng-include [duplicate]

2020-01-29 02:48发布

Here is the relevant html:

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

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

var trade = {
    order: {}
}

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

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

3条回答
对你真心纯属浪费
2楼-- · 2020-01-29 03:27

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

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

The cleaner solution is to make a new generic directive

Here's the ideal usage:

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

The directive is:

.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
    }
)

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.

查看更多
一纸荒年 Trace。
3楼-- · 2020-01-29 03:37

I answered a very similar question yesterday.

Same answer: use a directive with isolated scope

Multiple ngIncludes with Different controls visible

查看更多
够拽才男人
4楼-- · 2020-01-29 03:40

The solution is to create a new directive:

  angular.module('MyApp').directive('includeTemplate', directive);

  function directive() {
      return {
          templateUrl: function(elem, attrs) {
              return attrs.includeTemplate;
          },
          restrict: 'A',
          scope: {
              'includeVariables': '&'
          },
          link: function(scope, elem, attrs) {
              var vars = scope.includeVariables();
              Object.keys(vars).forEach(function(key) {
                  scope[key] = vars[key];
              });
          }
      };
  }

Here is the usage:

<div include-template="'myTemplate.html'" include-variables="{ var: 'myVar' }"></div>
查看更多
登录 后发表回答