0

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.