简体   繁体   中英

AngularJS with MVC dynamically get html, append to body, and bind a controller

I am new to AngularJS with a jQuery background. For what I thought would be a simple task I am just finding it to be increasingly difficult. I have looked around on how to dynamically add html and bind to a controller but I just have not found my particular situation.

This is what I am trying to accomplish. I'll want to keep it simple for now with a simple dialog box. Basically, suppose I want to create my own custom dialog box. Suppose based on a button click I want to display the message "Are you sure you want to so and so" with the buttons yes, no, cancel. Then based on the button click, I'd like to perform a specific operation, users with windows development will be familiar with this.

First I must construct my message and my dialog box html based on the button clicked, append that output html to the document body as position absolute, and then once done with this remove the html from the document body.

In jQuery I can simply do this

...somewhere in code
var html = "<div id='123' class='dialog-box'><button id='yesButton'></button>
...elements for no and cancel</div>";
DisplayDialog("123", html);
...

function DisplayDialog(elementId, html) {
    $(document.body).append(html);
    var dElement = $(document.body).find("#" + elementId);
    $(dElement).find("#yesButton").on("click" function () {
        ...code
        $(dElement).remove();
    });
    ...code for no, and cancel events
}

I just can't understand how to do this simply the angular way. Basically, I want to be able to get html, append it somewhere (whether in the body, or in a div element etc), and be able to interact with it using the $scope. I kept it simple for now for a dialog box, if I can understand this I can apply to much more complex operations where I might need to retrieve partial views in my MVC application and append it to a div

Its pretty straightforward in angular, this shouldn't be to hard for you given the jquery background:

var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.append('Hi<br/>');  

https://docs.angularjs.org/api/ng/function/angular.element

Another way:

You then use ng-bind in the html and set it to a $scope variable that represents the html:

<div ng-bind-html="divHtmlVar"></div>

$scope.divHtmlVar = '<b>main html</b>';

Relevant blog post:

http://blog.sodhanalibrary.com/2014/08/append-or-prepend-html-to-div-using.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM