Reputation: 1140
I am searching how to use double data-binding in angularjs respecting controller as style recommended by Google. It looks like:
hello.mainpage.HomeCtrl = function() {
/**
* @type {string}
* @export
*/
this.myColor = 'blue';
};
Cause I can't use $scope.$watch
or $scope.keypress
. What is the best way to do it?
Upvotes: 0
Views: 604
Reputation: 48211
Two-way data-binding is part of Angular's "magic" and is the process by which Angular automagically keeps the view in sync with the model. It shouldn't make any difference if you use the "normal" controller syntax with $scope or the "controller as" syntax without scope. Two-way-data-binding works in the exact same way.
E.g.:
"Controller" + "$scope":
<div ng-controller="someCtrl">
<input type="text" ng-model="someStr" />
</div>
.controller('someCtrl', function ($scope) {
$scope.someStr = 'Hello, world !';
});
Two-way data-binding works as usual.
"Controller as" + "no $scope":
<div ng-controller="someCtrl as ctrl">
<input type="text" ng-model="ctrl.someStr" />
</div>
.controller('someCtrl', function () {
this.someStr = 'Hello, world !';
});
Two-way data-binding works here as well.
On the other hand, if you want to $watch
something, then you need a $scope
(which the "controller as" syntax does not prohibit you from using).
All the above is nicely illustrated in this short demo.
Upvotes: 2