微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJS 如何从控制器组件外部调用控制器功能

我可以从网页的任何地方(控制器组件之外)调用控制器下定义的函数

它工作完美,当我按“获取”按钮。但我需要从外部的div控制器调用它。逻辑是:认情况下我的div是隐藏的。在导航菜单中的某处我按下一个按钮,它应该显示()我的div并执行“get”函数。我该如何实现呢?

我的网页是:

<div ng-controller="MyController">
  <input type="text" ng-model="data.firstname" required>
  <input type='text' ng-model="data.lastname" required>

  <form ng-submit="update()"><input type="submit" value="update"></form>
  <form ng-submit="get()"><input type="submit" value="get"></form>
</div>

我的js:

function MyController($scope) {
      // default data and structure
      $scope.data = {
        "firstname" : "Nicolas","lastname" : "Cage"
      };

      $scope.get = function() {
        $.ajax({
           url: "/PHP/get_data.PHP?",type: "POST",timeout: 10000,// 10 seconds for getting result,otherwise error.
           error:function() { alert("Temporary error. Please try again...");},complete: function(){ $.unblockUI();},beforeSend: function(){ $.blockUI()},success: function(data){
            json_answer = eval('(' + data + ')');
            if (json_answer){
                $scope.$apply(function () {
                  $scope.data = json_answer;
            });
            }
        }
    });
  };

  $scope.update = function() {
    $.ajax({
        url: "/PHP/update_data.PHP?",data: $scope.data,otherwise error.
        error:function() { alert("Temporary error. Please try again...");},success: function(data){ }
      });
    };
   }
这里是一个从外部调用控制器的函数方法
angular.element(document.getElementById('yourControllerElementID')).scope().get();

其中get()是来自控制器的函数

你可以切换

document.getElementById('yourControllerElementID')`

$('#yourControllerElementID')

如果你使用jQuery。

此外,如果你的函数意味着更改任何视图,你应该调用

angular.element(document.getElementById('yourControllerElementID')).scope().$apply();

以应用更改。

还有一件事,你应该注意,范围在页面加载后被初始化,因此从范围外调用方法应该总是在页面加载后完成。否则你根本不会到达范围。

更新:

有了最新版本的angular,你应该使用

angular.element(document.getElementById('yourControllerElementID')).injector().‌​get('$rootScope')

是的,这是,事实上,一个坏的做法,但有时你只需要做的东西快速和脏。

原文地址:https://www.jb51.cc/angularjs/147359.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐