I am a beginner in angularjs and currently I am facing an issue with ng-include.
I have a test app using partials. Here is my code.
<html ng-app ="TextboxExample">
<head>
<title>Settings</title>
<script src="angular.js"></script>
</head>
<body ng-controller="ExampleController">
<div ng-include src = "'view.html'"></div>
<script>
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.textboxVal = 'fddfd';
$scope.ReadGeneralSettings = function() {
alert($scope.textboxVal);
}
$scope.ResetGeneralSettings = function() {
$scope.textboxVal = 'fddfd';
}
}]);
</script>
<button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
<button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>
</body>
</html>
The partial code view.html is
<input type="text" ng-model="textboxVal">
For some reason, textboxVal set to ng-model doesn't get updated when I enter the value in the text box. But this works fine if I don't use ng-include and directly add the content of view.html into the main html file. Please help.
Thanks Sunil
Use $parent to access the scope of the controller
Demo
<input type="text" ng-model="$parent.textboxVal">
The problem is that ngInclude
creates new scope, so the model you define inside partial template with ngModel
works with local scope value, and outer ExampleController
can't see it.
The simple solution is to use prototypical chain of scope objects, then inner scope will inherit and use model value from the outer scope:
<body ng-controller="ExampleController">
<div ng-include src = "'view.html'"></div>
<script>
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.model.textboxVal = 'fddfd';
$scope.ReadGeneralSettings = function() {
alert($scope.model.textboxVal);
}
$scope.ResetGeneralSettings = function() {
$scope.model.textboxVal = 'fddfd';
}
}]);
</script>
<button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
<button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>
</body>
and then use it in partial as
<input type="text" ng-model="model.textboxVal">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With