Changing a parent controller model using the $ watch directive using controllerAs syntax

I am new to angular controller syntax and just trying to figure out how it works with the directive. I created one directive to verify the password. I want to make the flag true based on conditions, and they will be used in the parent template to display error messages. I do not understand how I can achieve this!

Jsfiddle

VIEW

<div ng-app="myapp">
    <fieldset ng-controller="PersonCtrl as person">
        <input name="emailID" type="text" ng-model="person.first" >
        <input name="pass" type="password" ng-model="person.pass" password-validator>
        <p ng-show="person.showMsg">Password validation message here.</p>
    </fieldset>
</div>

Directive

myapp.directive('passwordValidator',function() {
        return {
        controller : PasswordCtrl,
      controllerAs : 'dvm',
      bindToController : true,
      require : ['ngModel','passwordValidator'],
      link : function(scope,ele,attrs,ctrls) {
        var person = ctrls[1];
        var ngModelCtrl = ctrls[0];

        scope.$watch(function() {
                    return ngModelCtrl.$modelValue;
        },function(newVal) {
          if(newVal!='') {
            person.showMsg = true;
          } else {
            person.showMsg = false;
          }
          console.log(person.showMsg);
        });
      }
    }

    function PasswordCtrl() {

    }
});

Especially I want to understand why and how below the clock works fine!

// Why this below is also working, can anyone explain what going behind!! 
scope.$watch('person.pass',function(newVal) {
    console.log("Watch fires");
});

This is for training purposes only, so please explain how controllerAsand work bindToController!

+4
source share
2 answers

, , , ng-controller - -. , , , , .

, .

Angular bindToController , , scope: true scope: {}, .

.

ng- .

:

<fieldset ng-controller="PersonCtrl as person">

( ):

$scope.person = new PersonCtrl();

passwordValidator, controllerAs , :

$scope.dvm= new PasswordCtrl();

scope, :

$scope = {
    person = new PersonCtrl(),
    dvm: new PasswordCtrl()
}

person dvm . passwordValidator, , dvm. dvm, person.showMsg, , :

$scope.dvm.person.showMsg = <value>

dvm person, , $scope. $scope person. :

$scope.person.showMsg = <value>

, person , .

+1

, .

// Why this below is also working, can anyone explain what going behind!! 
scope.$watch('person.pass',function(newVal) {
    console.log("Watch fires");
});

, SAME scope .

this.checkDirCtrl = function() {
    console.log($scope.dvm);
}

this - undefined, controllerAs SAME, dvm , dvm .

, "" , . 'showMsg', , !

      if(newVal!='') {
        scope.person.showMsg = true;
      } else {
        scope.person.showMsg = false;
      }
      console.log(scope.person.showMsg);

: JSFiddle

+1

Source: https://habr.com/ru/post/1656168/


All Articles