简体   繁体   中英

Run script after view is loaded AngularJS

Im new at AngularJS, and i have this problem;

I fill part of my view with html from a variable in my controller:

<div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>

Everything goes fine until i decide to run a script. The script is shown, but it doesn't run. I think the problem is the view is filled with my variable controllers after loading the page, so the script doesn't run. The reason that i am using a variable in my controller to storage the script is because i will have to get the script from somewhere else, and its frequently changed.

Is this a viable way to run my script?.

Here is an example of my code:

View:

    <div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>

Controller:

    .controller('browseCtrl', function($scope,$sce) {

      $scope.video = '<div id="idxx1" style="width: 460px; height: 290px;" itemprop="video" itemscope itemtype="http://schema.org/VideoObject"></div><script>addeere3ejs("idxx1",  "172653", "24431581", "1_fq2w6oc2");</script>';

      $scope.deliberatelyTrustDangerousSnippet = function() {
      return $sce.trustAsHtml($scope.video);
    };
})

If my question it is unclear i would try to explain it better.

You can use the viewContentLoaded event in your controller.

$scope.$on('$viewContentLoaded', function(){
 // Run after view loaded.
});

Not exactly sure if ng-bind-html will allow a script to be ran like that. You may need to wrap it in angulars brackets to auto-run on load.

 <div ng-bind-html="{{deliberatelyTrustDangerousSnippet()}}"></div>

My work around was to run a $scope function like this with a known variable(s) that will change:

{{postBind(results)}}

Then have a method in your controller to do this

$scope.postBind = function (obj) {
        running_my_extenal_methods();
    }

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