从指令的独立的控制器? [英] Separate controller from directive?

查看:85
本文介绍了从指令的独立的控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新来这里的角。我创建一个顶级的导航指示,例如:

New to angular here. I'm creating a top-nav directive, like so:

<html>
<body ng-app="myApp">
    <top-nav></top-nav>
</body>
</html>

这工作正常。然而,让我们说我有顶级的导航需要调用topNav的控制器内的showLoginDialog()方法以外的按钮。

This works fine. However, let's say I have a button outside of the top-nav that needs to call the showLoginDialog() method within the topNav's controller.

为了这个工作,我需要将控制器从顶部导航像这样分离:

In order for this to work, I will need to isolate the controller from the top-nav like so:

<html>
    <body ng-app="myApp">
        <div ng-controller="TopNavController as topNav">
            <top-nav></top-nav>
        </div>
        <!-- assume more markup here.... -->
        <button ng-click="topNav.showLoginDialog()">
    </body>
</html>

我的问题是:这被认为是不好的做法?也就是说,从该指令取出控制器,以便东西以外可以访问它?

My question is: Is this considered bad practice? That is, removing the controller from the directive so that something outside can access it?

编辑:仅供参考 - 当您点击我的顶级导航登录按钮,我的登录弹出出现。不过,我也希望这个登录弹出,以便能够当一个人点击我主页上的巨人注册按钮,弹出。这就是为什么我问怎么把它从外面打电话。

推荐答案

如果在 showLoginDialog 是整个组件的共同作用而不会在同一层次存在,那么我觉得这是少了头痛,如果你简单地实现服务:

If the showLoginDialog is a common function across components which don't exist in the same hierarchy, then I find it to be less of a headache if you simply implement a service:

app.factory('login', function() {
  return {
    showLoginDialog: function() {
      // whatever
    }
  };
});

在您所提供的例子中,不会有任何范围继承,所以你将不能够从 topNav 访问方法。但是,如果你把服务/工厂常用的方法和属性,你现在给自己,通过它可以分享真理的唯一来源为整个应用程序的信息的一种机制。这是更多的角十岁上下的方式来做到这一点。

In the example you've provided, there won't be any scope inheritance, so you won't be able to access that method from topNav. However, if you place common methods and properties in services/factories, you've now given yourself a mechanism by which you can share a single source of truth for information across your application. This is the more "Angular-ish" way to do it.

要在你的控制器使用该服务,只需注入它:

To use the service in your controller, just inject it:

app.controller('topNav', function(login) {
  $scope.showLogin = login.showLoginDialog;
});

app.controller('registerCtrl', function(login) {
  $scope.showLogin = login.showLoginDialog;
});

取决于您的应用程序的结构,但在该机制可能发生变化,该​​政策将是相同的。

Depends on the structure of your app, but while the mechanism may change, the policy will be the same.

这篇关于从指令的独立的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆