Warning: Angular newbie ahead.

I have this code in an angular.js page

  <div class="clearfix" ng-controller="Controller">

    <h1>Active Ideas 
    <button type="button" ng-click="search()">get Ideas</button></h1>
    <hr>

and then I have defined my controller as:

function Controller($scope, $http) {
  $scope.search = function(){...

And it works fine.

I'd like to execute search() function when the dom is ready...

I tried calling it from a $(function() {... but I don't know how to manually execute a method from my controller

Also tried with

$scope.$on('$viewContentLoaded', function() {

But couldn't make it work (and couldn't find much documentation either...)

有帮助吗?

解决方案

You should execute search when your Controller is initialized. i.e.

function Controller($scope, $http) {
  $scope.search = function(){...};
  $scope.search();
}

When Angular's Dependency Injection constructs your controller then you know that the your view is compiled, linked, and ready for initialization code.

其他提示

Sometimes you need to wait for the first digest, otherwise your DOM will be ready but it won't have any value that you have set in your $scope, let's say an element with a ng-repeat linked to an array in your $scope won't be ready. For it to work properly you'll need to wrap your code in a $timeout(..., 0), this way your code will be executed immediately after the first digest.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top