javascript - AngularJS directive conditionally based on controller variable -


i want display error message invalid login credentials whenever user tries logs in through non-matching username , password combination (through request server, returns status invalid login details in case). have created directive same:

app.directive('invalid', function ($compile) {     return {         scope: true,         restrict: 'a',         link: function link(scope, element) {             element.bind('submit', function (){                 var text = '<div class="uk-alert uk-alert-danger" ng-if="invalidcredentials"><p>invalid username or password</p></div>';                 el = $compile( text )( scope );                 element.append(el);             });         }     } }); 

(notice ng-if on appended element)
have applied directive form element in following manner:
<form invalid name="loginform" ng-submit="loginuser(logindetails);" novalidate>

whenever user credentials invalid (checked through request made server), variable $scope.invalidcredentials set true (inside global controller).

it's working fine except fact directive triggers each time form submitted. [no matter value of $scope.invalidcredentials]. ng-if doesn't seem work.

please help. in advance

you used element.bind('submit', function () { ... } function called every time form submitted.

in function compile , append html is, regardless of ng-if in it. want forego directive @omri said, , put html code in form, so:

<form name="loginform" ng-submit="loginuser(logindetails);" novalidate>     ...     <div class="uk-alert uk-alert-danger" ng-if="invalidcredentials">         <p>invalid username or password</p>     </div> </form> 

now <div> show whenever invalidcredentials true.

note: use directives when have dom manipulation on element, or when element comes multiple times in code. in example assume use section once(on login page) there no need directive.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -