2014-11-20 60 views
0

我有一個問題涉及到AngularJS中的條件部分類似視圖。下面的例子不是非常優化的。它還返回屬於行$compile(element.contents())(scope)的錯誤,該錯誤表示我不能使用scope作爲函數 - 但否則它將無法正確渲染所有內容。使用情況如下:AngularJS中的條件視圖

  1. 我請求路由在$http返回對象

  2. ng-repeat是返回的對象數組

  3. 對於每一個對象的數組(讓我們稱之爲obj)給出了一個obj.view_edit值。

  4. 如果obj.type等於plugin,一個<plugin></plugin>指令插入

這將是這樣的:

<plugin view="content.view_edit"></plugin> 

我的指令看起來像:

directive('plugin', function($compile) { 
    var linker = function(scope, element, attrs) { 
     console.log(scope.view); 
     element.html(scope.view).show(); 
     $compile(element.contents())(scope); 
    } 
    return { 
     restrict:"E", 
     link: linker, 
     scope: { 
      view:'=' 
     } 
    } 
}) 

你有更好的解決方案?

回答

1

您應該不需要在鏈接函數中手動執行DOM操作來隱藏/顯示或$compile s,直到您處理更復雜的問題。只需使用本地ng-if指令。

<div ng-repeat="obj in objects"> 
    <div ng-if="isPlugin(obj)"> 
     <plugin view="obj.view_edit"></plugin> 
    </div> 
    <div ng-if="!isPlugin(obj)"> 
     This is not a plugin. 
    </div> 
</div> 

然後,您將在您的範圍內有ng-if引用的函數。這樣可以保持HTML更清晰並儘可能清除邏輯。

scope.isPlugin = function (obj) { 
    return obj.type === 'plugin'; 
} 
+0

謝謝!我用[ngSwitch](https://docs.angularjs.org/api/ng/directive/ngSwitch)'ng-switch =「content.type」'和'ng-switch-when =每個類型的「插件」。 – barfoos 2014-11-22 08:25:27