Javascript AngularJS如何从ng include指令返回承诺
我有一个ng include指令的视图。 该值绑定到模型Javascript AngularJS如何从ng include指令返回承诺,javascript,angularjs,angularjs-ng-include,Javascript,Angularjs,Angularjs Ng Include,我有一个ng include指令的视图。 该值绑定到模型 <div ng-app="mainModule"> <div id="mainController" ng-controller="mainController as main"> <div ng-include="main.guestUrl"></div> </div> </div> 然后在控制器中设置模型
<div ng-app="mainModule">
<div id="mainController" ng-controller="mainController as main">
<div ng-include="main.guestUrl"></div>
</div>
</div>
然后在控制器中设置模型
vm.goTo = function (url) {
$scope.$apply(function () {
vm.guestUrl = $sce.trustAsResourceUrl(url);
});
};
I can use the includeContentRequested event, but how do I return the promise ?
$scope.$on('includeContentRequested', function (e) {
});
现在我没有使用ng include,而是自己执行$http请求和$compile,这样我就可以返回一个承诺
vm.navigateTo = function (url) {
var deferred = $q.defer();
var promise = $http({
method: 'GET',
url: url
});
promise.then(function successCallback(response) {
var container = $('#mainContainer');
container.empty();
var html = response.data;
container.append(html);
$compile(container)($scope);
deferred.resolve('ok');
}, function errorCallback(reason) {
deferred.reject(reason);
});
return deferred.promise;
};
我认为使用ng include指令更干净
有人知道如何在includeContentRequested事件中返回承诺吗
我想出了这个代码,可以通知主机,但它是丑陋的。
因此,我想我应该继续我的$http调用
vm.goTo = function () {
var deferred = $q.defer();
$scope.$apply(function () {
vm.guestUrl = $sce.trustAsResourceUrl('http://localhost:63661/');
});
$scope.$on('$includeContentLoaded', function (args) {
deferred.resolve('ok');
$scope.$destroy('$includeContentLoaded');
});
return deferred.promise;
};
与使用ng include不同,我建议使用具有自己控制器和作用域的
这个范围是实现承诺的好地方(它是建立在变量之上的抽象)创建自己的简单指令而无需使用jQuery@charlietfl这是因为它是从另一个没有包含AngularJS的项目调用的,但是如果你正在进入AngularJS应用程序,可以简单地使用angular事件来更新一个方向,你实际上在做什么?因为它只是在请求内容时触发的事件。“我认为你不应该在listener中返回任何内容。@sielakos,我会再试一次,我知道这很混乱,我理解我的问题不清楚。”。但事实就是这样。我有一个像主持人一样的项目,没有AngularJS。这位主持人正在调用另一个项目,该项目表现得像一位来宾,与AngularJS合作。主机从客户机加载视图,但此客户机也有模板,即使用ng includes加载。主机必须知道何时加载这些模板。所以客人必须通知主人。如何做到这一点?这确实是一个想法。我会试试这个建议。谢谢
vm.goTo = function () {
var deferred = $q.defer();
$scope.$apply(function () {
vm.guestUrl = $sce.trustAsResourceUrl('http://localhost:63661/');
});
$scope.$on('$includeContentLoaded', function (args) {
deferred.resolve('ok');
$scope.$destroy('$includeContentLoaded');
});
return deferred.promise;
};