Reputation: 9555
Why is the watch not logging every time the model changes?
Why is the Input not beginning with the value test?
(function () {
'use strict';
// Create the application.
var app = angular.module('tabApplication', []);
// Creat the tabs controller.
app.controller('tabController', ['$log', '$scope', function ($log, $scope) {
$scope.myName = 'test';
$log.log($scope.myName);
$scope.$watch('myName', function(newValue, oldValue) {
$log.log(newValue, oldValue);
});
}]);
}());
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<body>
<div ng-app="tabApplication" ng-controller="tabController as tabC">
<p>Name : <input type="text" ng-model="tabC.myName"></p>
<h1>Hello {{tabC.myName}}</h1>
</div>
</body>
</html>
Upvotes: 0
Views: 133
Reputation: 5190
As cl3m answer pointed since you are using controller as syntax you have to watch for 'tabC.myName'
Another way to do it and stay to the controller as paradigm (i.e. have the controller be a constructor) is using this
for setting the variables, and importing $scope
to use the $watch
functionality
(function () {
'use strict';
// Create the application.
var app = angular.module('tabApplication', []);
// Creat the tabs controller.
app.controller('tabController', ['$log', '$scope', function ($log, $scope) {
this.myName = 'test';
$log.log(this.myName);
$scope.$watch('tabC.myName', function(newValue, oldValue) {
$log.log(newValue, oldValue);
});
}]);
}());
Upvotes: 1
Reputation: 468
The ng-model="tabC.myName"
is not binding to the $scope.myName
variable, that is why the input appears empty at the begining and not with 'test'.
try ng-model="myName"
instead ;)
Upvotes: 2
Reputation: 2801
Have you tried watching the string 'tabC.myName'
instead of juste watching 'myName'
:
$scope.$watch('tabC.myName', function(newValue, oldValue) {
$log.log(newValue, oldValue);
});
Upvotes: 4