Search code examples
htmlangularjsangularjs-directiveangularjs-ng-modelangularjs-ng-include

How to get different ng-model values in ng-include of the same HTML file


There are two html files:

index1.html

<input type="text" ng-model="model.Name">
<!-- Some complex form !-->

index.html

<div>Journalist's Details:
    Name:<div ng-include="index1.html"></div>
</div>
<div ng-if="isCompanionNeeded">Journalist's Companion Details:
    Name:<div ng-include="index1.html"></div>
</div>

Here ,I'd want "Journalist.Name" in place of the "model.Name" for the "Journalist's Details:" part of the form and "Companion.Name" in place of "model.Name" for the "Journalist's Companion Details: " part , as using the same model name will just get me same values in both the name fields and any other fields.


Solution

  • If you are using AngularJS v1.5+, you can use component instead of ng-include. This is an example of a component you could create

    Component JS

    angular
        .module('app')
        .component('myDetailsComponent', {
            bindings: {
                data: '<'
            },
            controller: function () {
                // do whatever you need with your input here            
            },
            templateUrl: 'my-details.component.html'
        });
    

    Component Template

    <input type="text" ng-model="$ctrl.data.Name">
    

    View

    <div>
        <p>Journalist's Details:</p>
        <my-details-component data="companion"></my-details-component>
    </div>
    

    Edit

    If you are using an older version of AngularJS, you can replicate the same functionality with a directive. For example:

    Directive JS

    angular
        .module('myDetailsDirective')
        .directive('myDetailsDirective', myDetailsDirective);
    
    
    function myDetailsDirective() {
    
        return {
            restrict: 'E',
            scope: {
                data: '='
            },
            templateUrl: 'my-details.directive.html',
            link: function () {
                // do whatever you need with your input here   
            }
        };
    
    }
    

    Directive Template

    <input type="text" ng-model="data.Name">
    

    View

    The usage of the directive is exactly the same as in the case of the component:

    <div>
        <p>Journalist's Details:</p>
        <my-details-directive data="companion"></my-details-directive>
    </div>