我正在尝试按以下方式使用 AngularJs 填充 html 列表。我想创建一个服务,它接受 html 部分,在构造函数中填充它的属性并返回它。下面是我的示例。
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl',['$scope','listElemService', function($scope,listElemService) {
$scope.listElemArray = [];
var testParam1 = {};
var tester = listElemService(testParam1);
$scope.listElemArray.push(new listElemService(testParam1));
var testParam2 = {};
testParam2.url = "http://www.yahoo.com";
testParam2.imgSrc = "https://pbs.twimg.com/profile_images/378800000416430559/3fab1a175e2a87010f23435e0aea0f61_400x400.jpeg";
$scope.listElemArray.push(new listElemService(testParam2));
}]).factory('listElemService',function(){
var ListElemConstructor = function(params) {
this.initialize = function() {
this.url = params.url;
this.imgSrc = params.imgSrc;
/*
want to be able to construct list element below
from listElemView.html based on params.url and params.imgSrc
*/
this.html = "Html Placeholder";
};
this.initialize();
};
return ListElemConstructor;
});
主要html:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.0-rc.1/angular.js" data-semver="1.4.0-rc.1"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="x in listElemArray">
{{x.html}}
</li>
</ul>
</body>
</html>
我想“引入”到我的服务并填充的 Html 部分:
<li>
<img src=""/>
<a href=""></a>
</li>
最佳答案
我不确定您是否需要x.html,似乎您需要或内联模板
<li ng-repeat="x in listElemArray">
<img src="{{x.imgSrc}}"/>
<a href="{{x.url}}"></a>
</li>
var app = angular.module('app', []);
app.controller('MainCtrl', ['$scope', 'listElemService',
function($scope, listElemService) {
$scope.name = 'World';
$scope.listElemArray = [];
var testParam2 = {};
testParam2.url = "http://www.yahoo.com";
testParam2.imgSrc = "https://pbs.twimg.com/profile_images/378800000416430559/3fab1a175e2a87010f23435e0aea0f61_400x400.jpeg";
$scope.listElemArray.push(new listElemService(testParam2));
console.log("$scope.listElem: ", $scope.listElemArray);
}
]).factory('listElemService', function() {
var ListElemConstructor = function(params) {
console.log("list elem const url: " + params.url);
this.initialize = function() {
this.url = params.url;
this.imgSrc = params.imgSrc;
var self = this;
};
this.initialize();
};
return ListElemConstructor;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
<ul>
<li ng-repeat="x in listElemArray">
<img ng-src="{{x.imgSrc}}" />
<a ng-href="{{x.url}}">{{x.url}}</a>
</li>
</ul>
</div>
或使用ngInclude
<li ng-repeat="x in listElemArray" ng-include="'listElemView.html'">
关于javascript - 使用 AngularJS 服务构建 html 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30148035/