Search code examples
javascriptangularjsangularjs-ng-modelng-view

ng-model is not working inside ng-view with global controller


It seems very simple but i could not fix it, my controller can not read ng-model related to input box inside ng-view. here are my codes

main.html

<html ng-app="myapp" ng-controller="main_controller">
<head>
    <title>test</title>
</head>
<body>
<section ng-view>
</section>
<!--Jquery-->
<script src="../jquery/jquery.js" type="text/javascript"></script>
<script src="../angularjs/angular.js" type="text/javascript"></script>
<!--Angular js-->
<script src="../angularjs/angular-route.js" type="text/javascript"></script>
<script src="../app.js" type="text/javascript"></script>
</body>
</html>

view.html

<input type="text" ng-model="input_value">
<button ng-click="read_input()">print</button>

app.js

var app = angular.module('myapp', ['ngRoute'])
app.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'view.html',
        })
})
app.controller('main_controller', function ($scope) {
angular.element(document).ready(function () {
    //some Ajax request
})
    $scope.read_input = function () {
        console.log($scope.input_value)
    }
})

When i write anything inside input box and press print button, it should prints data in the console log, but it gives me undefined. i know that i didn't provide controller at config of routeProvider but i included ng-controller at top of page it is because i want to use one controller for all of my views,as you see i have ajax request when the document is fully loaded, if i provide same controller for each page in the routeProvider at each chang of view my ajax will be called and i don't want this. Is there a better solution?


Solution

  • Try Below. Your controller scope is not reaching html.

    <div ng-controller="main_controller">
        <input type="text" ng-model="input_value">
        <button ng-click="read_input()">print</button>
    </div>