2015-09-25 75 views
0

AnglarJS newb在這裏尋找一些答案。我有這些文件,HTML和一個JSON文件,我想要做的就是使用在json中作爲屬性建立的鏈接,並在按鈕或鏈接標籤中使用它。如何使用對象值作爲AngularJS元素的href屬性?

的index.html

<!DOCTYPE html> 
<html> 
<script src=   "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
<body> 

<div ng-app="templateApp" ng-controller="templateCtrl"> 

<ul> 
<li ng-repeat="x in templates"> 
{{ x.title}} 
</li> 
<li ng-repeat="x in templates"> 
{{ x.limagen}} 
</li> 
<li ng-repeat="x in templates"> 
    {{x.lpagina}} 
</li> 

<a href ng-click="lpagina"> 
    <script> 
      lpagina={{x.lpagina}}; 
    </script> 

    Link</a> 

</ul> 

<img src="https://placeholdit.imgix.net/~text? txtsize=25&txt=400%C3%97100&w=400&h=100"></img> 

</div> 

<script> 
var app = angular.module('templateApp', []); 
app.controller('templateCtrl', function($scope, $http) { 
$http.get("obras.json") 
.success(function (response) {$scope.templates = response.obra;}); 
}); 
</script> 

</body> 
</html> 

而且JSON文件(obras.json)

{ 
    "obra": [ 
     { 
      "title": "Sample Text", 
      "limagen": "http://placehold.it/350x150", 
      "lpagina": "http://stackoverflow.com/questions/25335140/creating- a-button-link-with-json-params" 
     } 
    ] 

} 

感謝任何幫助,您可以給我!

+0

我開始了我的意見,因爲我很困惑,你要完成的任務。請用您想要的最終HTML示例更新您的問題。這裏有幾個問題,首先是錨內的奇怪腳本。 – isherwood

+0

我想在按鈕或href中使用json的值lpagina在html中,我對標記做了一個失敗的測試 –

回答

2

Angular允許{{ }}位於標籤內部。你也不需要把它寫成腳本,因爲它只是一個錨標籤。

<a href ng-click="lpagina"> 
    <script> 
     lpagina={{x.lpagina}}; 
    </script> 

Link</a> 

變爲:

<a href="{{x.lpagina}}">Link</a> 

Demo

+0

我有一個小提琴準備好,所以我在這裏添加它。請注意,我已將ng-repeat移至列表中。 – isherwood

+0

而其餘的代碼保持不變?只需將更新後的ref標籤放入div中?感謝你的回答! –

+0

不,您還需要刪除額外的腳本,將您的錨*移動到列表項(用於有效的html)中,並修復ng-repeat結構。看小提琴。 – isherwood