从角控制器分离DOM操作 - 最佳实践通缉 [英] Separating DOM manipulation from Angular controllers - Best Practice wanted

查看:137
本文介绍了从角控制器分离DOM操作 - 最佳实践通缉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图寻找最佳的方式建设一个角度应用我发现了几个最佳实践的文章。有了这个输入我这样做:

Trying to find the "best" way building an Angular App I found several best practice articles. With this input I did this:

angular.module('xApp', [])
//..... some services, factories, controllers, ....

.directive('dirNotification',[ function dirNotification() {
    return {
        scope: {}, 
        templateUrl: 'xNotification.html',
        replace: true,
        controller: 'CtrlNotification',
        link: function($scope){
            // if this is 'DOM manipulation, should be done here ... ?
            /*
            $scope.$on('session.update',function(event, args) {
                if (args == null) {
                    $scope.notificationdata.username = "";
                    $scope.notificationdata.sid = "";
                } else {
                    $scope.notificationdata.username = args.username;
                    $scope.notificationdata.sid = args.accessToken;
                }
            });
            */
        }

    };
}])
.controller('CtrlNotification',['$scope' ,function CtrlNotification($scope) {

    $scope.notificationdata = {
        username: "",
        sid: ""
    };

    // this is not real DOM manipulation, but only view data manipulation?
    $scope.$on('session.update',function(event, args) {
        if (args == null) {
            $scope.notificationdata.username = "";
            $scope.notificationdata.sid = "";
        } else {
            $scope.notificationdata.username = args.username;
            $scope.notificationdata.sid = args.accessToken;
        }
    });

}])

HTML模板很简单:

The HTML template is simply this:

<div>
    <p>{{notificationdata.username}}</p>
    <p>{{notificationdata.sid}}</p>
</div>

所以我的问题是,应数据的变化被认为是DOM操作?在present版本控制器内这样做似乎更实用,我(例如设置默认值)。另外,如果我添加更多功能的是,指令链接块将增长,含有比定义更多的功能。我想喜欢改变颜色或隐藏取决于范围的数据元素应该在那里进行指令的东西之内。

So my question is, should data changes to be considered as DOM manipulation? The present version doing this within the controller seems more practical to me (e.g. setting default values). Also if I add more functionality to that, the "directive link" block will grow and contain more functions than definitions. I guess within the directive things like changing colors or hiding elements depending on the scope data should be done there.

这是什么社会呢?你与我的假设同意吗?

What does the community mean? Do you agree with my assumptions?

谢谢,
莱纳

推荐答案

作为一个良好的开端,阅读<一href=\"http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background\">SO问题/答案。

As a good start, read this SO question/answer.

控制器:

在控制器中你不应该做的DOM操作的原因(或DOM元素的查找,或作出有关的任何视图的假设,对于这个问题)是因为控制器的目的是为了只的状态处理应用程序 - 通过改变视图模型 - 不论状态如何反映在视图中。该控制器确实是由模型和视图反应事件,并设置视图模型的属性。角将处理反映在绑定查看在App的状态。

The reason you shouldn't do DOM manipulation (or lookup of DOM elements, or making any assumptions about the View, for that matter) in the controller is because the intent of the controller is to deal only with the state of the app - by changing the ViewModel - irrespective of how the state is reflected in the View. This controller does that by reacting to events from the Model and from the View and setting properties of the ViewModel. Angular will deal with reflecting the "state" of the App in the View with bindings.

所以,是的,当然,改变视图模型使视图作出反应和DOM被操纵,但这个想法是控制器不应该知道或关心的观点是究竟是如何反应的。这使完好的关注点分离。

So, yes, of course, changing the ViewModel causes the View to react and DOM to be manipulated, but the idea is that the controller should not know or care about how exactly the View is reacting. This keeps the separation of concerns intact.

指令:

当内置指令是不够的,你需要关于更严格的控制的如何的视图反应是,这是一个很好的理由来创建自定义指令。

When built-in directives are not enough and you require tighter control about how the View is reacting, this is a good reason to create a custom directive.

两件事情要记住的指令。

Two things to remember about directives.

1),它认为作为指令可重用的组件中是非常有用的,所以较少应用程序特定的逻辑存在,就更好了。绝对,避免任何业务逻辑在那里。定义输入和输出(通常通过属性)和响应只对那些。事件侦听器(就像你有)有很大的应用程序特定的(除非该指令是为了与发布另外一个事件的指令中使用),所以最好尽量避免,如果可能的话。

1) It's useful to think of directives as re-usable components, so the less app-specific logic there is, the better. And definitely, avoid any business logic there. Define inputs and outputs (typically via attributes) and react only to those. Event listeners (like you have) are very app-specific (unless this directive is intended to be used with another directive that publishes an event), so better be avoided, if possible.

.directive("notification", function(){
  return {
    restrict: "A",
    scope: {
      notification: "=" // let the attribute get the data for notification, rather than
                        // use scope.$on listener
    },
    // ...
  }
})

2)仅仅因为指令允许做DOM操作并不意味着你应该忘掉视​​图模型 - 视图分离。角允许您定义范围链接或控制器功能里面,提供了一个模板,所有典型的前角pressions和绑定。

2) Just because directives are "allowed to do DOM manipulations" doesn't mean that you should forget about the ViewModel-View separation. Angular allows you to define scope inside a link or a controller function, and provide a template with all the typical Angular expressions and bindings.

template: '<div ng-show="showNotification">username:{{notification.username}}</div>',

// controller could also have been used here
link: function(scope, element, attrs){ 
   scope.showNotification = Math.floor(Math.random()* 2);    
}

这篇关于从角控制器分离DOM操作 - 最佳实践通缉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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