Search code examples
angularjsangularjs-directiveangularjs-scopeisolation

Isolated scope issue


I have almost no expertise when working with isolated scopes on angular but i found something for a project that i was using to check the strength of an username with an Angular directive.

This is the directive:

function usernameStrength() {
  return {
    require: 'ngModel',
    restrict: 'E',
    scope: {
      username: '=ngModel'
    },

    link: function(scope, elem, attrs, ctrl) {

      /** Watch password fields **/
      scope.$watch('username', function(newVal) {
        scope.strength = isSatisfied(newVal && newVal.length >= 8) +
          isSatisfied(newVal && /[A-z]/.test(newVal)) +
          isSatisfied(newVal && /(?=.*\W)/.test(newVal)) +
          isSatisfied(newVal && /\d/.test(newVal));

        function isSatisfied(criteria) {

          return criteria ? 1 : 0;

        }
      }, true);
  }
}

Then on my HTML (JADE) i had an input and the directive on whom the strength progress bar is displayed and manipulated.

input.form-control(autocomplete="off", type='text', required='', ng-model="register.username")

label Strength username-strength(ng-model="register.username")

Till here everything works fine, but then if i add an object on the controller to store all the data from the form (which is a wizard) and set the input ng-model like this ng-model="register.data.username" (Same thing on the username-strength directive) Being data in the controller this object

vm.data  = {};

The $watches in the directive no longer have access to the input.


Solution

  • With your code, you are putting the username-strength on the label while the your directive is just triggered only for the element with name 'user-strength'. It is wrong way, so the $watch does not work.

    1. The ngModel binds an input,select, textarea, not the label.
    2. You have to modify the restrict to 'A' instead of 'E', and put it into the your input[text]

    Fixed

    You are trying to track the status of text field username and print something like the strength of the text on the label. You can study on from this sample. (source)