javascript - Angularjs, create customer directive with $http.post -
i new angularjs, have input form email.
<div ng-app="emailapp" ng-controller="emailcontroller"> <form name="emailsubmitform"> <div> <input name="emailinput" type="email" ng-model="email" ng-watchchange="checkduplicate(email)" ng-pattern="emailformat" required /> </div> <div ng-show="isrepeated">repeated</div> <div ng-show="!isrepeated">not repeated</div> <button ng-disabled="emailsubmitform.$invalid" ng-click="createrecord()" >submit</button> </form> </div>
originally use ng-change not fire if invalid, therefore want change ng-change function directive, have no idea how it.
i want change function below
$scope.checkduplicate = function (email) { var model= { email: email }; $http({ method: 'post', url: '/controller/isemailduplicated', data: model }).success(function (data, status, headers, config) { $scope.isrepeated = !data; }); };
to like
app.directive('ngwatchchange',function(email){ // $http.post request });
could give me suggestions? lot!
i use $watch if can't use ng-change (in controller or in separated directive, wouldn't go way). in controller:
$scope.$watch(function () { return $scope.email }, function (changedemail) { var model= { email: email }; $http({ method: 'post', url: '/controller/isemailduplicated', data: model }).success(function (data, status, headers, config) { $scope.isrepeated = !data; }); });
this way, you'll send $http on every email change (but can personalize want).
if still persist on using directive, try:
app.directive('ngwatchchange', function() { return { restrict: 'a', scope: { ngwatchchange: '=' }, link: function(scope, element, attr) { $scope.$watch(function () { return scope.ngwatchchange }, function (changedemail) { var model= { email: email }; $http({ method: 'post', url: '/controller/isemailduplicated', data: model }).success(function (data, status, headers, config) { $scope.isrepeated = !data; }); }); } }; });
Comments
Post a Comment