问题
So I am working on a project that will allow a user to modify a template. The base template will be made up for components and the user will be able to add or remove components. I found a few things online - such as grapeJS but it is far to intense for this simple application.
Looking for some advice on a way to go about this, or any resources that will help.
Here is a basic example.
Basic template will consist of these components
- Header
- Text Post
- Single Image
- Footer
The list of components a user can choose from to add to template mught consist of..
- Image Slideshow
- Video
- 2 Column Text Post
- Automatic wav file player of Wrecking Ball by Miley Cyrus
The user will be able to select from that above list and append to the template list above.
Any thoughts or inputs to get me going in the right direction would be helpful!
回答1:
This should set you in the right direction:
- Create your Image Slideshow, Video, 2 Column Text Post, and Miley Cyrus Video as AngularJS components or directives that work on their own.
- In the directive/component where you want to dynamically load the components/directives you created above, use
$compile
to compile your components. Then, use$element
to add your compiled element to the DOM.
I've created a barebones implementation of this, where myTemplate
represents the template that holds the main template of your application. The directive slideshow
represents the Image Slideshow that is dynamically added to the page when the user clicks on Add Component
.
HTML
<div>
<my-template></my-template>
</div>
JavaScript
var myApp = angular.module('myApp',[]);
myApp.directive('myTemplate', function($rootScope, $compile) {
return {
controller: function($element, $scope) {
var vm = this;
vm.name = "name";
vm.insert = function() {
var elStr = "<slideshow></slideshow>";
var newScope = $rootScope.$new();
var insertedEl = $compile(elStr)(newScope);
$element.append(insertedEl);
};
},
controllerAs: "vm",
template: "<h1>Header</h1><p>Body</p><footer>Footer</footer><button ng-click='vm.insert()'>Add Component</button>"
}
});
myApp.directive("slideshow", function() {
return {
controller: function() {
this.text = "THIS IS A SLIDESHOW";
},
controllerAs: "vm",
template: "<h1>{{vm.text}}</h1>"
}
});
Click here for a working JSFiddle.
来源:https://stackoverflow.com/questions/47557552/angularjs-dynamically-add-component-from-list