我在玩使用JQuery和AngularJS的網站項目。 $http
用於瀏覽器和服務器之間的REST通信。該網站的網址是localhost:8080/myproject
。因此,每個頁面或資源都有一個路徑/myproject/someresource
。爲了能夠容易地構建這些路徑我使用數據屬性的body
元件上:如何在AngularJS函數中加載數據屬性?
<!DOCTYPE html>
<html>
...
<body data-url="myproject">
</body>
的data-url
的實際值通過JSP的<c:url value="/" />
是動態生成的。現在我想使用此屬性爲$http
方法構建一些路徑。爲此,我使用JQuery:
var path = $('body').attr('data-url');
然而,我不得不等待DOM產生的結束,所以以前被包裹:
var path;
$(function() {
path = $('body').attr('data-url');
}
在另一方面,我有一個AngularJS $scope
功能,用於按鈕:
<button ng-click="foo()">click</button>
...
var mainApp = angular.module('main', [ 'ngResource' ]);
mainApp.controller('myController', function($scope, $http) {
$scope.foo = function() {
$http.get(path + 'folder').success(function(response) { /* do crazy stuff */ });
};
}
爲了編譯角碼代碼,它可能不會被包裹在$
函數中,如path
的定義。因此,path
將不會在控制器定義時設置。我發現的唯一的解決辦法是移動的foo()
定義內$()
和存儲$http
在$scope
:
mainApp.controller('myController', function($scope, $http) {
$scope.$http = $http;
}
$(function() {
var path = $('body').attr('data-url');
var $scope = angular.element($('main')).scope();
var $http = $scope.$http;
$scope.foo = function() {
$http.get(path + 'folder').success(function(response) { /* do crazy stuff */ });
};
}
是否有此問題的任何清晰的解決方案?我的方法看起來像一個骯髒的黑客...
難道你不能簡單地使用' '標籤嗎? –
sp00m
2014-11-25 15:35:42
你能解釋爲什麼你需要在_data-url_中動態加載路徑嗎?如果沒有必要這樣加載它,你可以使用「plain」AngularJS進行靜態配置... – arman1991 2014-11-25 18:13:34
@ sp00m我可以使用這個標籤。但是這並不能解決AngularJS的控制器在完成DOM設置之前需要定義的主要問題,這個問題反過來需要在我可以通過JQuery查詢屬性之前完成。 – Bastian 2014-11-26 07:58:11