简体   繁体   中英

filter user input in angularjs

I built something in angular using ng-repeat

            <ul class="messages">
                <li ng-repeat="e in enquiries">
                    <img src="/img/avatar.jpg" alt="">
                    <div>
                        <div>
                            <h5>{{e.user}}</h5>
                            <span class="time"><i class="fa fa-clock-o"></i> {{e.created_at}}</span>
                        </div>
                        <p>{{e.post}}</p>
                        <div ng-if="e.is_replied == 'no'"><a href="/hub/delete">Delete</a></div>
                    </div>
                </li>
            </ul>

This is to display the inputs by users. However i did not htmlentities to encode the user input but directly insert the user input into database such as <a href="jscode">Hack</a> However i notice when i display this message using above code. it will still display the message as <a href="jscode">Hack</a> instead of display a " hack " link. can i say in this case angular will auto sanitize the input? Should i still need to use "ng-bind-html"?

If your post content is HTML you will need to change to ng-bind-html:

<p ng-bind-html="e.post | to_trusted"></p>

Also you will need a filter to sanitize:

app.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}])

Your best bet is the $sanitize service, part of the ngSanitize module. Use the ng-bind-html directive, which automatically uses $sanitize . ng-bind-html will insert your text as raw HTML, but only if it's in the ngSanitize white list of safe HTML. If you're absolutely sure the HTML is safe (eg, if you sanitize it on the back end), there's a way to tell Angular to stuff it in as is, regardless of the white list.

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