【问题标题】:How to load a function when a controller is called in angularjs在angularjs中调用控制器时如何加载函数
【发布时间】:2017-02-25 18:18:34
【问题描述】:

我有一个功能

        state('showList', {
            url: '/listView',
            templateUrl: 'app/templates/showlist.html',
            controller: "showListCtrl"
        }).

我的控制器,

.controller('overViewCtrl', function ($scope) {
    $scope.getList = function(){
        //A http call
    }
 });

当我的路由更改为“/listView”时,会调用 overView 控制器,但不会调用函数 getList(),但是当我刷新页面时会调用我。谁能帮帮我。我只是想调用它在控制器加载的那一刻起作用。谢谢。

当我的路线更改为“/listview”时

【问题讨论】:

    标签: javascript angularjs controller mean-stack angularjs-routing


    【解决方案1】:

    你可以在外面的函数里面声明代码,

    .controller('overViewCtrl', function ($scope) 
        //put it here without a function 
    
     });
    

    也可以在页面上使用ng-init调用函数

    【讨论】:

    • 如果我放在那里有一个错误 getlist is not a function.
    • 你不需要getlist
    【解决方案2】:
    .controller('overViewCtrl', function ($scope) {
        $scope.getList = function(){
            //A http call
        }
      $scope.getList() //just call it here
    
     });
    

    或者我建议您最初使用 resolve 获取数据

    https://medium.com/opinionated-angularjs/advanced-routing-and-resolves-a2fcbf874a1c#.t127bl60d

    【讨论】:

      【解决方案3】:

      您可以使用 ui-router 的 resolve 函数来保持控制器更精简,但在控制器加载后仍然可以访问解析的数据

      // router
      $stateProvider.state('myState', {
        resolve: {
          simpleObj: function(){
            return {value: 'simple!'};
          }
        }
      }
      
      // controller
      ['simpleObj', function(simpleObj) {
        console.log(simpleObj); // ==> value: 'simple!'
      }]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        相关资源
        最近更新 更多