更新时间:2022-04-12 22:16:31
目前尚不清楚您要实现的目标(我很确定会有更好的方法),但您可以这样做:
It is not clear what you are trying to achieve (I'm pretty sure there will be some better way), but you could do it like this:
1.
在您的范围内定义承诺:
1.
Define a promise in your scope:
app.controller('myCtrl', function ($http, $scope) {
$scope.model = {
promise: $http.get('/my/service'),
myField01: 'Hello, world, from 01 !',
myField02: 'Hello, world, from 02 !',
myField03: 'Hello, world, form 03 !'
};
});
2.
在您的 HTML 中,引用该承诺以将其传递给您的指令:
2.
From your HTML, reference that promise in order to pass it to your directive:
<input type="text" my-field="model.promise" />
3.
将此承诺纳入指令的隔离范围:
3.
Get this promise into your directive's isolate scope:
app.directive ('myField', function ($compile) {
return {
scope: { promise: '=myField' },
...
4.
在您的 link
函数中,注册一个回调,以在承诺得到解决时(即您收到对您的请求的响应)并进行所有必要的操作:
4.
In your link
function, register a callback for when the promise gets resolved (i.e. you get a response to your request) and do all necessary manipulation:
...
link: function (scope, elem, attrs) {
scope.promise.success(function (data) {
elem.removeAttr('my-field');
elem.attr('ng-model', 'model.' + data.fieldName);
$compile(elem)(scope.$parent);
});
}
另请参阅此简短演示.