2015-09-04 24 views
1

我有一個JSON結構,從那裏,我創建一個使用控制器和路線的窗體。 JSON的是:如何使用自定義數據進入ng-if? (angularJS)

[{ 
    "name": "home", 
    "section": "link" 
}, 
{ 
    "name": "about", 
    "section": "link" 
}, 
{ 
    "name": "Style", 
    "section": "link" 
},{ 
    "name": "name", 
    "type": "text", 
    "section": "home" 
}, 
{ 
    "name": "age", 
    "type": "text", 
    "section": "home" 
}] 

而且JS代碼是:

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

myApp.controller("linkCtrl", function($scope, dataService, $route) { 
    dataService.getData('json/link.json', function(data){ 
     $scope.links = data.data; 
     $scope.message = "home";  
    }); 
}); 

和我的HTML代碼是:

<h4>{{message}}</h4> 
<div ng-repeat="item in links"> 
    <div ng-if="item.section == 'home'"> 
     <div ng-switch="item.type"> 
      <div ng-switch-when="text"> 
       <input type="text" id={{item.name}} /> 
      </div> 
      <div ng-switch-when="button"> 
       <button id={{item.name}}>{{item.name}}</button> 
      </div> 
      <div ng-switch-when="checkbox"> 
       <input type="checkbox" id={{item.name}} /> 
      </div> 
     </div> 
    </div> 

此代碼工作正常。如果我使用ng-if="item.section == {{message}}"ng-if="item.section == '{{message}}'",它不起作用,但在ng之外 - 如果我把{{message}},它顯示「home」。

爲什麼它不在ng-if語句內工作。基本語法在我的代碼本身中提到。我剛剛發佈了我的函數的主代碼

如果代碼在ng-if中工作,那麼它將很容易爲我的頁面使用一個模板。

那麼,有什麼辦法可以使它工作嗎?

+3

刪除引號和括號。即。 'item.section ==消息' – Johan

回答

2

使用

ng-if="item.section == message" 

代替

ng-if="item.section == {{message}}" 
+1

你是對的,但我認爲我最好展開爲什麼是這種情況。 Angular將通過你的標記來查看雙曲花括號並注入它們(也可以替換花括號)模型的插值。然而,對於角度指令,'ng-show'' ng-if'等需要對模型屬性的引用,以便Angular可以在其上執行數據綁定,並在模型更改時動態更改值。 – ste2425

0

你將不得不使用它像 NG-IF = 「item.section ===消息」

見NG-如果是一個指令,並已在範圍內。 ng-if原型從其父項繼承範圍。 ng-if需要你給出的表達式作爲「item.section ===消息」,因此不需要做任何嵌套插值,消息將被評估,因爲它在父範圍內。

相關問題