2016-02-12 78 views
0

因此,我有一個像這樣的指令,但它很好用,但我希望如此,如果用戶將IP地址更改爲「192.168.3.10」或將網關更改爲「192.168.3.1」,則所有三個字段均標記爲無效。角度輸入驗證其他輸入?

本質上,如果一個字段被標記爲無效,則將其他兩個字段標記爲無效。

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

myApp.controller("MyCtrl", ["$scope",function($scope) { 
$scope.IPAddress = "192.168.1.10"; 
$scope.Gateway = "192.168.1.1"; 
$scope.Netmask = "255.255.255.0"; 
}]); 
myApp.directive("networkCheck", function() { 
    return { 
    require: 'ngModel', 
    scope: { 
     otherIp: "=", 
     netmask: "=" 
    }, 
    link: function(scope, elem, attrs, ctrl) { 
     var sameNetwork = function(ipOne, ipTwo, netmask) { 
     console.log(ipOne, ipTwo, netmask); 
     if (!ipOne || !ipTwo || !netmask) { 
     return true; 
     } 
     var components1 = ipOne.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); 
     var components2 = ipTwo.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); 
     var subcomps = netmask.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); 

     if (components1 === null || components2 === null || subcomps === null) { 
     return; 
     } 

     var ip1 = parseInt(components1[1]); 
     var ip2 = parseInt(components1[2]); 
     var ip3 = parseInt(components1[3]); 
     var ip4 = parseInt(components1[4]); 

     var sp1 = parseInt(components2[1]); 
     var sp2 = parseInt(components2[2]); 
     var sp3 = parseInt(components2[3]); 
     var sp4 = parseInt(components2[4]); 

     var sn1 = parseInt(subcomps[1]); 
     var sn2 = parseInt(subcomps[2]); 
     var sn3 = parseInt(subcomps[3]); 
     var sn4 = parseInt(subcomps[4]); 

     var octa1 = ip1 & sn1; 
     var octa2 = ip2 & sn2; 
     var octa3 = ip3 & sn3; 
     var octa4 = ip4 & sn4; 
     var octb1 = sp1 & sn1; 
     var octb2 = sp2 & sn2; 
     var octb3 = sp3 & sn3; 
     var octb4 = sp4 & sn4; 

     if ((octa1 == octb1) && (octa2 == octb2) && (octa3 == octb3) && (octa4 == octb4)) { 
     return true; 
     } else { 
     return false; 
     } 
    }; 

    ctrl.$validators.networkCheck = function(modelValue) { 
     return sameNetwork(modelValue, scope.otherIp, scope.netmask); 
    }; 

    scope.$watch("ipCheck", function() { 
     ctrl.$validate(); 
    }); 
    } 
} 
}); 

http://jsfiddle.net/t55fLhry/1/

回答

1

有一件事你可以做的是通過形式進入你的指令,然後設置一個$watch,並通過模型的控制器檢查每個模型的有效性。這將允許您更新的所有輸入有效性他們隨時一個有變化:

看到此更新的jsfiddle:http://jsfiddle.net/q2fLz54t/

標記

<input type="text" name="ipaddress" network-check ng-model="IPAddress" form="IPForm"/> 

指令

... 
scope.$watch("ngModel", function(newValue, oldValue) { 
    if (newValue !== oldValue) { 
    sameNetwork(scope.form.gateway, scope.form.ipaddress, scope.form.netmask); 
    } 
}); 
... 
var sameNetwork = function(ipOne, ipTwo, netmask) { 
    ...  
    // set validity in your checking function 
    ipOne.$setValidity('network-check', true); 
    ipTwo.$setValidity('network-check', true); 
    netmask.$setValidity('network-check', true); 
    ... 
} 
+0

這是太棒了!從來沒有想過要通過形式本身。我必須保留這些隱藏的信息。很簡單。 – Charlie