简体   繁体   中英

Accessing Angular controller within a script

Currently, I have some code like this

<div id="{{id}}" ng-controller="ngController as ngCtrl" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <!-- Removed some non important html -->
        <script src="/static/jstree/dist/jstree.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $.getJSON("/book/modules", function(d) {
                    var moduleDiv = $("#module-div")
                    moduleDiv.jstree({
                        core: {
                            data: d
                        }
                    });
                    moduleDiv.on("select_node.jstree", function(e, data) {
                        ngCtrl.selectedModule = data;
                    });
                });
            });
        </script>
    </div>
</div>

This code is contained within an angular directive.

app.directive("modulesModal", function(){
    return {
        scope: {
            label: "@",
            input: "@",
            ngController: "=",
            id: "@"
        },
        templateUrl: "/static/book_config/html/modules-modal.html",
        link: function($scope, $elem, $attrs){
            // Non important stuff
        }
    };
});

So what I'm really trying to do is access some controller variables here

moduleDiv.on("select_node.jstree", function(e, data) {
    ngCtrl.selectedModule = data;
});

This way I can just plugin my controller to it via the directive tag: Eg

<modules-modal id="myModal" ng-controller="newBookCtrl"></modules-modal>

What is the correct way to go about this?

The way you combine jquery and angular is by creating an angular directive, which you did. However, you should move your jquery code inside the directive instead of doing it externally and passing the data to the directive. You can create a directive controller in this case, and then load your json data in the controller itself instead. It should be something like this (untested code):

 app.directive("modulesModal", function(){ return { scope: { label: "@", input: "@", //ngController: "=", <- you don't need to pass in a controller id: "@" }, templateUrl: "/static/book_config/html/modules-modal.html", link: function($scope, $elem, $attrs){ // Non important stuff }, controller: function ($scope) { $.getJSON("/book/modules", function(d) { var moduleDiv = $("#module-div") moduleDiv.jstree({ core: { data: d } }); moduleDiv.on("select_node.jstree", function(e, data) { $scope.selectedModule = data; }); }); } }; }); 

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