angularjs 實現 window.onload() $(document).ready() 的4種方法

習慣了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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章