AngularJS 在模板指令中显示 HTTP 请求的结果
AngularJS show result of HTTP request inside directive in template
我试图在第一次加载 AngularJS (1.6) 指令并在指令模板中显示其结果时发出 GET 请求。
目前我正在尝试的是:
JS:
app.directive("myDirective", ['$http', function($http) {
return {
restrict: 'AE',
attrs: {
foo : String,
onResponse : function(response){
this.foo = response.data;
}
},
templateUrl: 'templates/my-directive.html',
compile: function(scope, element, attrs) {
$http({
method: 'GET',
url: 'my/url'
}).then(
attrs.onResponse
);
}
}
}]);
HTML 模板:
<div id="my-directive">
foo: <span>attrs.foo</span>
</div>
有没有办法正确地做到这一点?
提前致谢!
好吧,我通过添加控制器成功地完成了我想做的事情:
app.directive("myDirective", ['$http', function($http) {
return {
restrict: 'AE',
controller: "myDirectiveController",
templateUrl: 'templates/my-directive.html'
}
}]);
哪里
app.controller('myDirectiveController', function ($scope, $http) {
$scope.foo;
$scope.onResponse = function(response){
$scope.foo= response.data;
}
$http({
method: 'GET',
url: 'my/url'
}).then(
$scope.onResponse
);
});
模板如下所示:
<div id="my-directive">
foo: <span>{{foo}}</span>
</div>
这可能不是正确的方法,但它确实有效。欢迎提出任何建议!
我试图在第一次加载 AngularJS (1.6) 指令并在指令模板中显示其结果时发出 GET 请求。
目前我正在尝试的是:
JS:
app.directive("myDirective", ['$http', function($http) {
return {
restrict: 'AE',
attrs: {
foo : String,
onResponse : function(response){
this.foo = response.data;
}
},
templateUrl: 'templates/my-directive.html',
compile: function(scope, element, attrs) {
$http({
method: 'GET',
url: 'my/url'
}).then(
attrs.onResponse
);
}
}
}]);
HTML 模板:
<div id="my-directive">
foo: <span>attrs.foo</span>
</div>
有没有办法正确地做到这一点?
提前致谢!
好吧,我通过添加控制器成功地完成了我想做的事情:
app.directive("myDirective", ['$http', function($http) {
return {
restrict: 'AE',
controller: "myDirectiveController",
templateUrl: 'templates/my-directive.html'
}
}]);
哪里
app.controller('myDirectiveController', function ($scope, $http) {
$scope.foo;
$scope.onResponse = function(response){
$scope.foo= response.data;
}
$http({
method: 'GET',
url: 'my/url'
}).then(
$scope.onResponse
);
});
模板如下所示:
<div id="my-directive">
foo: <span>{{foo}}</span>
</div>
这可能不是正确的方法,但它确实有效。欢迎提出任何建议!