renaming a variable in ng-include [duplicate]
Asked Answered
G

3

1

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?

Garb answered 6/3, 2015 at 22:51 Comment(0)
E
2

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.

Extrajudicial answered 25/10, 2015 at 18:21 Comment(0)
C
0

I answered a very similar question yesterday.

Same answer: use a directive with isolated scope

Multiple ngIncludes with Different controls visible

Charitycharivari answered 6/3, 2015 at 22:55 Comment(0)
C
0

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>
Calyces answered 28/4, 2016 at 13:32 Comment(1)
This solution treats your include-variables data as static. It won't track changes that occur in the parent scope. With a lot more effort, you could actually have 2-directional binding of changes to the include-variables data: https://mcmap.net/q/89055/-angularjs-how-to-render-a-partial-with-variablesMarried

© 2022 - 2024 — McMap. All rights reserved.