【问题标题】:calling ng-view controller method from outside controller?从外部控制器调用 ng-view 控制器方法?
【发布时间】:2014-09-08 02:46:12
【问题描述】:

HTML:

<html ng-app="san">
<head>
</head>
<body ng-controller="sanctrl">
<div>
    AngularJS</div>
<div ng-view="">
</div>
<button type="button" ng-click="init()" class="btn btn-blue">
    Save</button>
</body>
</html>

主控制器:

san.controller('sanctrl', function ($scope, $http, $q, $location, $anchorScroll, $filter, dataFactory) {
//nothing in this controller.
});

ng-view 控制器:

san.app.controller('cereals', function ($scope, dataFactory) {
  $scope.init(){
    $scope.test = "test";
  };
});

我正在尝试从 ng-view 范围之外调用 init 方法。可能吗?如果没有,那么我们有哪些选择?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope angularjs-service angularjs-routing


    【解决方案1】:

    您可以使用您触发的广播事件:

      $rootScope.$broadcast('testEvent', testArray);
    

    然后在第二个控制器中你可以监听事件:

      $scope.$on('testEvent', function(event, array) {
    
          // Do stuff here
    
       });
    

    【讨论】:

      【解决方案2】:

      作为@lulu88,您可以使用$broadcast 做其他事情

      编写一个单独的服务将int()函数中的代码移动到那个,然后你可以从任何控制器访问它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-21
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多