javascript - 在 $http.get 的 AngularJS 指令中加载模板属性
问题描述
我是使用 angularjs 的新手,我正在尝试创建指令。我的查询是,如何$http.get
从 html 更改 URL。这是我的代码:
HTML指令:
<form-directive text="Formulario con Directiva" nameinput="true"
namelabel="Nombre:" emailinput="true"
emaillabel="Email:" subjetinput="true" subjetlabel="Asunto:"
message="true" messagelabel="Mensaje:"
dataurl="URL to change">
</form-directive>
JS:
<script>
angular.module('testDirective', [])
.controller('testDir', function ($scope, $http) {
$scope.textoFalopa = "Hola, es una prueba";
})
.directive('formDirective', function () {
return {
restrict: "EA",
templateUrl: './template.html',
scope: {
text: '@',
nameinput: '=nameinput',
namelabel: '@',
emailinput: '=emailinput',
emaillabel: '@',
subjetinput: '=subjetinput',
subjetlabel: '@',
message: '=message',
messagelabel: '@',
dataurl:'='
},
controller: ['$scope', '$http', function ($scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/users').then(function (remotedata) {
console.log(remotedata.data);
$scope.data = remotedata.data;
});
}],
link: function (scope) {
console.log(scope);
}
};
});
</script>
谢谢!
解决方案
我假设您要做的是获取指令声明中属性的值,dataurl="URL to change"
并将其用作 $http 调用中的 URL。
对象中的属性scope
定义了这些属性与您的 AngularJS 范围的绑定(注入为$scope
)。
您已经绑定dataurl
到您的范围,所以您已经完成了一半。现在,在您发布的示例中获取 最直接的方法是仅使用$scope
控制器中的对象。像这样:
angular.module('testDirective').directive('formDirective', function () {
return {
restrict: "EA",
templateUrl: './template.html',
scope: {
text: '@',
nameinput: '=nameinput',
namelabel: '@',
emailinput: '=emailinput',
emaillabel: '@',
subjetinput: '=subjetinput',
subjetlabel: '@',
message: '=message',
messagelabel: '@',
dataurl:'='
},
controller: ['$scope', '$http', function ($element, $http) {
$http.get($scope.dataurl).then(function (remotedata) {
console.log(remotedata.data);
});
}]
};
});
请注意,AngularJS 的最佳实践现在只$scope
在需要它的高级功能时直接使用。对于这种简单的情况,您不需要注入它。我建议查看 AngularJS组件和/或bindToController
属性。
如果您只想获取属性,另一种(但可能是混乱的)解决方案是注入$element
,它使您可以访问底层的 jQuery 对象。
angular.module('testDirective').directive('formDirective', function () {
return {
restrict: "EA",
templateUrl: './template.html',
controller: ['$element', '$http', function ($scope, $http) {
$http.get($element.attr('dataurl')).then(function (remotedata) {
console.log(remotedata.data);
});
}]
};
});
虽然这不是真正的“角度方式”,但我只会将它用于快速破解或凌乱的解决方法。
所以你有三种方法。任何一个都可以,但我建议学习组件和控制器绑定,因为这将鼓励良好的实践并让你有利于学习 Angular 2+
推荐阅读
- printing - 打印问题:Power BI 报告在打印期间在 Mozilla 和 Chrome 中被切断
- javascript - 使用 window.find 获取所有事件
- java - 带参数的 CrudRepository 查询
- html - 有什么方法可以将视频放入所有设备和所有浏览器的单个屏幕中
- c# - fo-DICOM:如何在 DicomClient 中指定本地传出端口?
- opengl - 在 OpenSceneGraph 场景中显示 Qt Quick 内容
- html - 引导元素容器类导致另一个引导元素发生变化
- nginx - 配置 nginx 以在 VPS 上托管 React 应用程序
- python - 如何有效地计算pyspark中的平均值和标准差
- java - 迁移到 JDK11 改变了必须从 Maven 运行测试的方式