2015-04-23 45 views
1

我正在接收數據到我的我的$scope作爲包含客戶端的各種細節的對象。我有以下型號對角度的驗證

client.name 
client.email 
client.programme 

在我的函數,我希望確保每個鍵都有一個值,沒有什麼是未定義的。

我以爲我可以使用||所以通過每一個檢查一個if語句中的undefined,但這是行不通的。

例如:

$scope.addClient = function(newClient) { 

console.log(newClient); 

    if(!newClient.name ||!newClient.email) { 
    $rootScope.$emit('errorEvent', 
    {"message" : "You must enter some client name"} 
    ); 
    }; 

...performing other functions... 

} 

其次我想用一個變量在錯誤消息中,這樣我可以它調整到是未定義的值。

回答

1

您沒有將$ scope附加到變量。

使用本

$scope.addClient = function(newClient) { 

    if(!newClient){ 
     $rootScope.$emit('errorEvent', 
     {"message" : "You must enter some client name"}); 
    } 

    else if(!$scope.newClient.name || !scope.newClient.email) { 
     $rootScope.$emit('errorEvent',{"message" : "You must enter some client name" }); 
    } 
    } 

$scope.addClient = function(newClient) { 

    if(newClient && (!$scope.newClient.name || !scope.newClient.email) || !newClient){ 
       $rootScope.$emit('errorEvent', 
       {"message" : "You must enter some client name"}); 
      } 

      } 
+0

請參閱我的編輯 - 這個我s被用在使用$ scope的函數中... – Taylorsuk

+0

我認爲事件傳播不工作.replace $ emit to $ broadcast。 –

+0

我剛剛在'!newClient.name'上得到一個錯誤,無法讀取undefined的屬性 – Taylorsuk

0

我最後不得不這樣做:

if(!client){ 
     $rootScope.$emit('errorEvent', 
     {"message" : "You must enter a client name"}); 
    } 

    else if(client.name === undefined) { 
     $rootScope.$emit('errorEvent',{"message" : "You must enter a client name" }); 
    } 

    else if(client.email === undefined) { 
     $rootScope.$emit('errorEvent',{"message" : "You must enter a client email" }); 
    } 

    else { 

REST OF FUNCTION 

} 

高興地收到建設性的批評/選項,以降低該代碼...