dylanjha
dylanjha

Reputation: 2513

ng-include on load with an object

This works

<div ng-include="template.html" onload="person='Jane'"></div>

^ This sets the local scope variable person in the include to 'Jane' (string)

But I want to pass a person object that is called user: {name: 'Jane' }

<div ng-include="template.html" onload="person=user"></div>

^ This sets the local scope variable person in the include to be 'undefined'

How is it possible to pass an object as a local variable to ng-include?

Upvotes: 0

Views: 1757

Answers (2)

Tanin
Tanin

Reputation: 1933

ng-include is not that reusable because it doesn't offer a way to set local variables. Using onload is bad because it litters the global scope. If the example gets a little more complicated, it'll fail.

Making a new directive instead of using ng-include is a cleaner solution.

The ideal usage looks like:

<div ng-include-template="template.html" ng-include-variables="{ person: 'Jane' }"></div>
<div ng-include-template="template.html" ng-include-variables="{ person: user }"></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, the directive reads the object from ng-include-variables and add those members to its own local scope.

This is clean and generic.

Upvotes: 1

Jonathan Wilson
Jonathan Wilson

Reputation: 4305

Maybe what you actually want is a custom directive:

<div person-directive="{name:'Jane'}"></div>

JS:

angular.module('myApp',[])
.directive('personDirective',function(){
    return {
        restrict: 'A',
        scope: {
            person: '=personDirective'
        },
        templateUrl: 'template.html'
    };
});

With this, you bind the passed-in value to person in the loaded template.

Working fiddle

Upvotes: 1

Related Questions