Ritesh Puri Ritesh Puri - 6 months ago 12
AngularJS Question

Implementing function using custom directive in AngularJS

I need help. I am learning how to create a custom directive. I am trying to implement a function using custom directive. I searched online but didn't find a suitable solution. My HTML code looks like :

<custom-search>
<input type="text" ng-model="displayname" placeholder="Enter your name here" />
<h1>Welcome {{displayname}}!!</h1>
</custom-search>


My JS file has custom directive as follows:

myApp.directive('customSearch', function () {

return {

restrict: "EA",

template: "<b>Hello my directive</b>",
}
});


I want to implement a function inside a custom directive so that I am not able to type further if the length of "displayname" reaches 60.

I have a logic as follows:

if ($scope.displayname.length > =60) {
if ($scope.displayname.length === 60) {
$scope.temp = $scope.displayname;
return;
}
if ($scope.displayname.length > 60) {
$scope.displayname = $scope.temp;
return;
}
return;
}
}

Answer

Write a directive function which has input param as fieldLimit which will be used to monitor. Set value of this input to your field: displayName. Add a limit number for it which will be used as limit of your input text.

Use watch to monitor on your input change.

app.directive('customSearch', function () {
return {
    restrict: "EA",
    scope : {
      fieldLimit: '='
    },
    link: function($scope, $element, $attr) {
      var limit = $attr.limit;
       $scope.$watch('fieldLimit',function(value){
         console.log('changed:' + value);
         if (value != null && value.length > limit)
         {
           $scope.fieldLimit = value.substring(0,limit);
         }
       })
    }
}
});

Then use it anywhere such as with a input text:

<div custom-search field-limit='displayName' limit='5'>
  <input type='input' ng-model='displayName'  />
</div>

Plunk example here: https://plnkr.co/edit/1S8yiu?p=preview