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?

scniro
  • 16,844
  • 8
  • 62
  • 106
pQuestions123
  • 4,471
  • 6
  • 28
  • 59

3 Answers3

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.

Tanin
  • 1,853
  • 1
  • 15
  • 20
0

I answered a very similar question yesterday.

Same answer: use a directive with isolated scope

Multiple ngIncludes with Different controls visible

Community
  • 1
  • 1
Reto
  • 3,107
  • 1
  • 21
  • 33
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>
smartmouse
  • 13,912
  • 34
  • 100
  • 166
  • 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: http://stackoverflow.com/a/17876761/361609 – colllin Apr 28 '16 at 20:50