1

Here my code:

index.html:

<head>
   <script src="angular.js"></script>
   <script src="angular-route.js"></script>
   <script src="script.js"></script>
</head>
<body>
    <div ng-view></div>
</body>
</html>

script.js:

var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
        $routeProvider.when('/', {
                templateUrl: 'route.html',
                controller: 'RouteController',
            }).otherwise('/');
}]);

app.controller('RouteController', ['$scope', function($scope) {
    $scope.hello='world';
}]);

app.controller('IncController', ['$scope', function($scope) {
    $scope.field = '';
    $scope.test = function() {
        console.log('test=' + $scope.field);
    }
}]);

route.html:

<div>
hello world
<div>{{hello}}</div>
<ng-include src="'including.html'"
            ng-controller="IncController"></ng-include>
</div>

including.html:

<input type='text' ng-model='field'/>
<input type='button' ng-click='test()'/>

When I click button test() function is calling, but field is always empty. If I make route for including.html it works when I go to this route.

nuclear kote
  • 480
  • 7
  • 16

1 Answers1

1

The reason is you have used ng-include while rendering including.html. As when you used ng-include it creates a child scope which is prototypically inherited from the parent scope.

You need to follow the dot rule while defining ng-model in such cases, which will tend to use Prototypal Javascript Inheritance & will take value from the object.

You need to define one object called model which will have various property in it, like $scope.model = { 'field': '' }

Markup

<input type='text' ng-model='model.field'/>
<input type='button' ng-click='test()'/>

Controller

app.controller('IncController', ['$scope', function($scope) {
    $scope.model = { 'field': '' };
    $scope.test = function() {
        console.log('test=' + $scope.model.field);
    }
}]);

Edit

You could also write your own directive like ng-include which load a template from URL but it will not create a child scope.

You could refer this approach here

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299