2016-06-08 28 views
-1

我有一個很長的一行if語句在ng中 - 如果在我的html中。它太長了,所以我想做一個函數來評估它。如何返回AND和OR邏輯運算符JavaScript

我的問題是,我不能讓我圍繞着如何「轉換」的& &或頭||嵌套if語句,我可以在一個函數中。能有人比我更聰明一些,能幫助我嗎?

這是我要轉換爲嵌套的if語句邏輯(我縮進它讓我在做什麼):

ng-if="(
    (
    (filter === 'critical') 
    || 
    (
     !(
     (filter === 'status') 
     || 
     (filter === 'events') 
    ) 
     && 
     (
     (
      !(door.status_error_array.length >= 1) 
      && 
      (door.event_array.length >= 1) 
     ) 
     || 
     (
      !(door.status_error_array.length >= 1) 
      && 
      !(door.event_array.length >= 1) 
     ) 
    ) 
    ) 
) 
    && 
    (door.critical_error_array.length >= 1) 
)" 
+2

我不明白你的意思 - 如果你有邏輯的工作,爲什麼不能你只需動動手,爲一個函數模型? – Jamiec

+0

我不知道該怎麼做......我不認爲我可以這樣寫嗎?我認爲我需要用if語句來編寫它?不是嗎? – pandaseal

+0

@pandaseal'if(/ * current contents * /)'? –

回答

1

推動這一邏輯控制器。只有非常簡單的表達方式才能進入視圖。

編輯

的第一步將是一個簡單的複製粘貼,如果您使用的是$範圍,而不是controllerAs語法,你需要預先this.$scope,在表達否則只是this

YourController.$inject = ['$scope']; 
function YourController($scope) { 
    this.$scope = $scope; 
} 

YourController.prototype.testExpresstion = function() { 
    return (
    (
    (this.$scope.filter === 'critical') 
|| 
(
    !(
    (this.$scope.filter === 'status') 
    || 
    (this.$scope.filter === 'events') 
) 
    && 
    (
    (
     !(this.$scope.door.status_error_array.length >= 1) 
     && 
     (this.$scope.door.event_array.length >= 1) 
    ) 
    || 
    (
     !(this.$scope.door.status_error_array.length >= 1) 
     && 
     !(this.$scope.door.event_array.length >= 1) 
    ) 
) 
    ) 
    ) 
     && 
     (this.$scope.door.critical_error_array.length >= 1) 
    ) 

} 

您的觀點也只是簡單地是這樣的:

<div ng-if="testExpression()"> 

當然不叫它testExpression。根據它的作用給它一個上下文名稱。

一旦你的工作,寫這個方法的單元測試。然後重構此方法,並將每個條件移入自己的方法,直到任何開發人員對此應該做的事情變得清楚。

+0

是的,就像我在問題中寫的那樣,我打算這麼做。問題是:如何將thml中的邏輯「轉換」爲控制器中的某些東西。 – pandaseal

+0

那麼它是如何工作的?同樣的語法,但只是在函數中返回? :3然後我明白我的問題聽起來很奇怪,我會試試! – pandaseal