简体   繁体   中英

How to use angular.js variable inside the script tag?

I am displaying some elements on a view using angular.js and trying to connect these dom elements using jquery connections.The elements are getting displayed properly but I am not able to use them inside the sscript tag.

<div ng-repeat = "impact in activity.text" style=" margin-right: auto;background: rgb(255, 255, 255);
                                      background: rgba(255, 255, 255, 0.7);
                                      min-width: 4em;
                                      min-height: 3em;
                                      max-width: 29ex;
                                      margin: 1.2em;
                                      padding: 0.6em;

                                      word-wrap: break-word;
                                    border: 1px solid rgb(200, 200, 200);
                                    border: 1px solid rgba(0, 0, 0, 0.2);
                                    border-radius: 16px;
box-shadow: 2px 5px 5px rgba(0,0,0,0.2);"  class="impact\{{$index}}" id="">

    \{{impact}}</div>


<script>
    $(document).ready(function() {


        $('div.impact\{{$index}}').connections({ from: 'div.actors' }).length;
        var connections = $('connection, inner');
        setInterval(function() { connections.connections('update') }, 10);
    });

</script>


</div>

Here I am generating unique class name for every element. But I get the error in console when I use the same value in script tag.

Uncaught Error: Syntax error, unrecognized expression: div.impact{{$index}}

在此处输入图片说明

There's an error in your logic, $index represents the current ng-repeat's iteration index, which doesn't exist outside of the loop itself, for obvious reasons.

Do you want to run this JS code for each generated DIV? You could move the script tag inside the loop, but Angular doesn't parse script tags, as mentioned by charlietfl.

You could write a directive and attach it to the ng-repeat DIV as an attribute:

angular.module('myApp').directive('updateConnections', function($interval) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.connections({ from: 'div.actors' }).length;
            var connections = angular.element('connection, inner');
            $interval(function() { connections.connections('update') }, 10);
        }
    };
});

To use the directive:

<div update-connections ng-repeat="impact in activity.text">...</div>

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