Search code examples
angularjsangularjs-ng-include

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?


Solution

  • 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