指令相互干扰

时间:2017-03-17 09:20:46

标签: javascript angularjs

我有2个指令与以下相同:

function signUpForm(djangoAuth, Validate){
 return{
    restrict:'A',
    controller:["$rootScope","$scope",function($rootScope, $scope){
       $scope.submitFunction = function(formData){
        //do stuff 
      }
    }]
 }}

 function signInForm(djangoAuth, Validate){
 return{
    restrict:'A',
    controller:["$rootScope","$scope",function($rootScope, $scope){
       $scope.submitFunction = function(formData){
        //do stuff 
      }
    }]
 }}

我的HTML如下:

<div>
  <div class="email_log_container">
     <form name="signup_form" class="signup_form" sign-up-form
           novalidate ng-submit="submitFunction(signup_form)">

           <input type="submit" name="submit" value="Submit" >

     </form>
  </div>

  <div class="email_log_container">
     <form name="signin_form" class="signin_form" sign-in-form
           novalidate ng-submit="submitFunction(signin_form)">

           <input type="submit" name="submit" value="Submit" >

     </form>
  </div>
</div>

问题是,当我单击第二个表单上的提交按钮时,它实际上会提交导致错误的第一个表单。所以我继续在指令中添加隔离范围,现在发生的是控制器中附加到$ scope的函数和属性现在没有被提取。例如,ng-submit不知道控制器中的submitFunction。

任何人都可以帮助我解决如何阻止这两个指令相互干扰的想法吗?

1 个答案:

答案 0 :(得分:0)

当您使用控制器但没有指令的模板时,这将无效。像在runnable demo fiddle中一样尝试,并将表单作为模板添加到您的指令中。通过这种方式,您将能够处理指令控制器本身的所有$scope善良。模板本身将被编译并使用指令控制器。

视图

<div ng-controller="MyCtrl">
  <div class="email_log_container"> 
    <sign-in-form></sign-in-form>
  </div>
</div>

AngularJS应用程序

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
});

myApp.directive('signInForm', function signInForm(){
  return{
    restrict:'E',
    replace: true,
    template: '<form name="signin_form" class="signin_form" sign-in-form novalidate ng-submit="submitFunction(signin_form)"><input type="submit" name="submit" value="Submit" ></form>',
    controller:["$rootScope","$scope",function($rootScope, $scope){
      $scope.submitFunction = function(formData){
        //do stuff 
        console.log('sdfsdfd');
      }
    }]
}});