【发布时间】:2017-05-10 10:33:32
【问题描述】:
我需要从 json 文件加载 html。所以我发现dform 是最好的解决方案。因为它是 jQuery 插件,我在 Angular 中需要它。我很幸运在jsfiddle 上找到了它的指令。
唯一的区别是我有自己的 json 文件,并且我已经单独编写了代码。我正在使用服务通过 http 请求从 json 文件中获取数据。 之后,我使用类似于 jsfiddle 的指令。
app.js
var app = angular.module('angularApp', []);
service.js
app.service('loaderService', ['$http', function ($http) {
this.getLoadedHtml = function (callback)
{
return $http.get('../source/file.json')
.then(function (res) {
callback(res.data);
});
}
}])
controller.js
app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) {
loaderService.getLoadedHtml(function (data) {
$scope.fields = data;
});
}]);
directive.js
app.directive('dform', function () {
return {
scope: {
action: '@',
method: '@',
html: '='
},
link: function (scope, elm, attrs) {
var config = {
"action": scope.action,
"method": scope.method,
"html": scope.html
};
elm.dform(config);
}
};
})
index.html
<div class="container-fluid" ng-app="angularApp">
<div ng-controller="mainCtrl" style="background-color:green; margin-top:100px; height:1000px;">
<div class="col-sm-3" id="source-area">
<div action="index.html" method="get" html="fields" dform></div>
</div>
</div>
</div>
file.json
[
{
"type": "p",
"html": "You must login"
},
{
"name": "username",
"id": "txt-username",
"caption": "Username",
"type": "text",
"placeholder": "E.g. user@example.com"
},
{
"name": "password",
"caption": "Password",
"type": "password"
},
{
"type": "submit",
"value": "Login"
}
]
我也使用过 jquery 和 dform 库。
因为我没有任何错误。我的数组在控制器中运行良好,并且 $scope.fields 在控制器中也运行良好。通过我看不到任何呈现的 html?我用的和 jsfiddle 一样。
【问题讨论】:
-
使用 jquery 插件的方法毫无意义。 json 看起来像什么以及它的预期结果是什么。这应该可以使用角度模板和一些数据映射轻松实现
-
@charlietfl 为什么它在 jsfiddle 中运行?问题是,为什么不在我的代码中运行?
-
但是你为什么要这样做呢?强烈建议您阅读stackoverflow.com/questions/14994391/…
-
我知道将 Jquery 与 Angular js 一起使用并不是一个好习惯。我无法在 Angular 中找到这个插件的替代品。
-
虽然我同意其他评论员的观点,但对于您的具体问题,我敢打赌,问题是
elm.dform(config);只运行一次,它不知道 html 更改。所以我会尝试在html属性上创建一个$watch,然后在回调中再次调用elm.dform(config);。
标签: javascript jquery html angularjs json