angularjs 實現 window.onload() $(document).ready() 的4種方法
阿新 • • 發佈:2019-02-19
習慣了window.onload(),$(document).ready(),現在換成別的了,還真有點不習慣了。下面說一下常用的4種情況。
1,html中直接寫
<script src="lib/angular/angular.min.js" type="text/javascript"></script> <script type="text/javascript"> angular.element(window).bind('load', function() { alert('1'); }); alert('2');</script>
不建議,直接在模板裡面,寫js程式碼。
2,在controller裡面利用$on或者$watch
bookControllers.controller('bookctrl_test', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.$on('$viewContentLoaded', function() { alert('1'); }); alert('2'); }]);
bookControllers.controller('bookctrl_test1', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.$watch('$viewContentLoaded', function() { alert('1'); }); alert('2'); }]);
3,利用data-ng-init
<div ng-controller="test"> <div data-ng-init="load()" ></div> </div>
注意:data-ng-init在controller裡面才會啟作用
bookControllers.controller('testInit', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.load = function() { alert('code here'); } }]);
源引:http://blog.51yip.com/jsjquery/1599.html