0

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?

dylanjha
  • 2,303
  • 4
  • 28
  • 47
  • possible duplicate of http://stackoverflow.com/questions/13422966/how-to-specify-model-to-a-nginclude-directive-in-angularjs – Jonathan Wilson Jun 28 '14 at 00:58
  • I don't think this is a duplicate. Correct me if I'm wrong, `ng-init` is not solving it for me, let me see if I can get a jsfiddle going to demonstrate – dylanjha Jun 28 '14 at 01:01
  • A solution is create a new directive, as i said in this answer: http://stackoverflow.com/a/36916276/2516399 – smartmouse Apr 28 '16 at 13:34

2 Answers2

1

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

Jonathan Wilson
  • 4,138
  • 1
  • 24
  • 36
1

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.

Tanin
  • 1,853
  • 1
  • 15
  • 20