Skip to content Skip to sidebar Skip to footer

Renaming A Variable In Ng-include

Here is the relevant html: Attached to the scope this ng-include is nested in is a trade variable. The trade var

Solution 1:

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:

<divng-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()
        forkey, 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.

Solution 2:

I answered a very similar question yesterday.

Same answer: use a directive with isolated scope

Multiple ngIncludes with Different controls visible

Solution 3:

The solution is to create a new directive:

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

  functiondirective() {
      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:

<divinclude-template="'myTemplate.html'"include-variables="{ var: 'myVar' }"></div>

Post a Comment for "Renaming A Variable In Ng-include"