Search code examples
angularjsangularjs-scopeangularjs-ng-include

access value from one template to other in angular


How to use model value from one template1 to template2 ?

Here is my code :- index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example84-production</title>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-animate.js"></script>
  <script src="script.js"></script>



</head>
<body ng-app="includeExample">
  <div ng-controller="ExampleController">
     <div ng-include="'template1.html'"></div>
    <div ng-include="'template2.html'"></div>

</div>
</body>
</html>

template1.html

Content of template1.html
<br/>
<input ng-model="x"/>

template2.html

Content of template2.html
<br/>
x={{x}}

Plukr- http://plnkr.co/edit/HF1KxLzGbmP4S7gVc5fQ?p=preview


Solution

  • Just use the "controller as" syntax :

    <body ng-app="includeExample">
      <div ng-controller="ExampleController as ex">
         <div ng-include="'template1.html'"></div>
        <div ng-include="'template2.html'"></div>
    
    </div>
    

    and inside your templates :

    x={{ex.x}}
    
    
    <input ng-model="ex.x"/>
    

    plunkr :

    http://plnkr.co/edit/FVkSj2vs8WDAt1eifBpF?p=preview