问题
Is there an AngularJS equivalent to $.load()
in jQuery? I want to be able to pull from another domain (i.e. post the app on one domain, but load content from a completely separate address).
回答1:
jQuery methods of usage don't really fit Angular, you won't find load
equivalent there (you obviously can use jQuery instead of jqLite if you want it badly).
Angular proposes the usage of ngInclude directive for similar off-hand scenarios. Otherwise you need to make your own directive and write the result from $http
request to element, especially if you need more control.
If you want to 'get content from a particular div', you will need to have jQuery loaded anyway to use selectors on response, something like this would be an equivalent for load
:
app.directive('load', function ($http, $compile) {
return {
link: function (scope, element, attrs) {
$http.get('link.htm').success(function (response) {
var contents = angular.element("<div>").html(response).find("#someelement");
element.empty().append($compile(contents)(scope));
});
}
}
});
回答2:
I reckon you can do it using ng-include . It has got a built-in onLoad method you can call to get your data from the remote address by using $http or $resource modules.
回答3:
Is there an AngularJS equivalent to $.load() in jQuery?
In normal case, you can write some code in a controller of angularjs instead of $.load function in jQuery.
Your code is going to be something like this.
angular.module('YourModule', [])
.controller('YourController', function($http){
// You can write some code here !!
//$http.get(...
//$http.post(...
});
I want to be able to pull from another domain (i.e. post the app on one domain, but load content from a completely separate address).
My advice depends on whether your content includes HTML tags or not.
If NOT including HTML tags, you could write the code like above.
If including HTML tags, I recommend to write some custom directive code.
回答4:
I make refresh directive and call on click event with compile and it works for me
.directive('refreshConfirm', function($http,$compile) {
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {
element.bind('click', function () {
$http.get(page_url).then(successCallback, errorCallback);
function successCallback(response){
//success code
var ty=response.data;
var appi=angular.element(document.querySelector('#page_content')).html($compile(ty)(scope));
}
function errorCallback(error){
//error code
alert('error');
}
});
}
};
})
来源:https://stackoverflow.com/questions/29223437/jquery-load-equivalent-angularjs