angular js中的控制器和指令之间有什么区别? [英] What is the difference between controller and directives in angular js?

查看:59
本文介绍了angular js中的控制器和指令之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular js的初学者.我正在努力了解angular js中的控制器和指令之间的确切区别.

解决方案

这里有太多的事情无法完全解释每个例子,因此我将尝试对每个例子以及示例进行简要说明.

控制器

使用控制器来处理视图的逻辑并分配要在视图中显示的数据.例如,如果在您的应用程序中有一个名为所有用户"的页面,您想显示一个用户列表,定义一个用户数组并将其附加到控制器中的$scope对象.

var myApp = angular.module('myApp',[]);

myApp.controller('allUsersController', ['$scope', function($scope) {
  $scope.users = [
    { name: "User 1", id: 1},
    { name: "User 2", id: 2},
    { name: "User 3", id: 3}
  ];
}]);

将users数组附加到合并范围可让您从视图访问此数据.因此,现在您可以在视图中使用 ng-repeat 输出用户列表:

<ul>
 <li ng-repeat="user in users">{{user.name}}</li>
<ul>

指令

指令主要用于两件事:

  1. 创建可重复使用的组件
  2. 操纵DOM

伪指令一开始使用起来很棘手,但功能非常强大,文档中的此语句是它们如此强大的原因:

伪指令是DOM元素(例如 属性,元素名称,注释或CSS类)来说明AngularJS的 HTML编译器($ compile)将指定的行为附加到该DOM 元素(例如,通过事件监听器),甚至可以转换DOM 元素及其子元素.

要摆脱的主要观点是,指令允许您将某些逻辑/行为附加到某些元素,而作为控制器,通常只允许您将逻辑附加到页面/视图./p>

让我们说,在上一个示例中,我们希望添加一些可以在用户列表中完成的操作,例如喜欢"和不喜欢"按钮.我们可以像这样创建喜欢和不喜欢的按钮:

JS

var myApp = angular.module('myApp',[]);

myApp.controller('allUsersController', ['$scope', function($scope) {
  $scope.users = [
    { name: "User 1", id: 1, like: 0},
    { name: "User 2", id: 2, like: 0},
    { name: "User 3", id: 3, like: 0}
  ];

  $scope.like = function(user){
    user.like++;
  }

  $scope.dislike = function(user){
    user.like--;
  }
}]);

HTML

<ul>
 <li ng-repeat="user in users"> 
   {{user.name}}
   <button ng-click="like(user)">LIKE</button>
   <button ng-click="dislike(user)">DISLIKE</button> 
 </li>
<ul>

相当简单,我们在控制器中添加了like/dislike方法,以增加/减少用户的喜欢次数.这段代码可以正常工作,但是如果我想在不同的视图中创建另一个用户列表怎么办?假设您有3个不同的视图,其中包含用户列表:所有用户",我的朋友"和推荐用户",所有这3个用户都将拥有具有相同操作(喜欢或不喜欢)的用户列表,但是显示的用户是各自不同.我们想使用在allUsersController中定义的like/dislike方法,但是我们在不同的视图上,因此我们无法访问它们,因此您必须将相同的代码复制到其他视图的控制器中,在我们的示例中,看起来似乎没什么大不了的,但是随着应用程序变得越来越大,越来越复杂,这变得非常乏味且难以维护.

这是指令进入的地方,您可以在指令中定义它,而不是在控制器中分配每个用户项目背后的逻辑:

app.directive('userItem', function() {
return {
    template: '<div>{{userData.name}} <button ng-click="like()">Like</button> <button ng-click="dislike()">Dislike</button>',
    scope: {
      userData: "="
    },
    link: function(scope, element, attrs) {
      scope.like = function(){
       scope.userData.like++;
      }

      scope.dislike = function(){
       scope.userData.like--;
      }
    }
}
});

在您的html中:

<div class="user_list>
   <user-item ng-repeat="user in users" user-data="user"></user-item>
</div>

通过使用user-item指令,您现在可以在应用程序中的任何位置创建用户列表,而不必重新定义每个用户附带的逻辑.您会注意到,这也清理了我们的html并节省了很多重复代码的时间.该指令将您的html和js包装为可重用组件.

关于我们如何将用户数据传递给指令,这与指令中的隔离范围有关,您可以阅读userData范围.

您可以访问指令文档,然后向下滚动以隔离范围以获取更多示例.

>

I am the beginner of angular js. I am struggling to understand the exact difference between the controller and directive in angular js.

解决方案

There's a bit too much going on here to be able to fully explain each so i'll try to give a brief explanation of each as well as an example.

Controllers

Use controllers to handle the logic of your views and assign the data you want to appear in your view. For example if in your application you have a page called "All Users" you want to display a list of users you would, define an array of users and attach it to the $scope object in your controller.

var myApp = angular.module('myApp',[]);

myApp.controller('allUsersController', ['$scope', function($scope) {
  $scope.users = [
    { name: "User 1", id: 1},
    { name: "User 2", id: 2},
    { name: "User 3", id: 3}
  ];
}]);

Attaching the users array to the scope allows you to access this data from the view. So now in the view you can use ng-repeat to output the list of users:

<ul>
 <li ng-repeat="user in users">{{user.name}}</li>
<ul>

Directives

Directives are mainly used for 2 things:

  1. Creating reusable components
  2. Manipulating the DOM

Directives are tricky to use at first but are extremely powerful, this statement from the docs is the reason why they are so powerful:

Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.

The main point to take away from that is that directives allow you to attach certain logic/behavior to a certain element, where as controllers usually only allow you to attach logic to pages/views.

Lets say that in the previous example we wanted to add some actions that can be done in the user list, maybe a like and dislike button. We could just create like and dislike buttons like this:

JS

var myApp = angular.module('myApp',[]);

myApp.controller('allUsersController', ['$scope', function($scope) {
  $scope.users = [
    { name: "User 1", id: 1, like: 0},
    { name: "User 2", id: 2, like: 0},
    { name: "User 3", id: 3, like: 0}
  ];

  $scope.like = function(user){
    user.like++;
  }

  $scope.dislike = function(user){
    user.like--;
  }
}]);

HTML

<ul>
 <li ng-repeat="user in users"> 
   {{user.name}}
   <button ng-click="like(user)">LIKE</button>
   <button ng-click="dislike(user)">DISLIKE</button> 
 </li>
<ul>

Fairly simple, we add like/dislike methods in our controller that increment/decrement the amount of likes a user has. This code will work fine, but what if i wanted to create another list of users in a different view? Say that you have 3 different views which contain user lists: "All Users", "My Friends" and "Recommended Users", all 3 will have a list of users that have the same actions (like or dislike) but the users displayed are different in each. We want to use the same like/dislike methods that we defined in our allUsersController but we are on a different view so we can't access them, so you would have to copy the same code into the controllers of the other views, might not seem like a big deal in our example but as applications get larger and more complicated this gets very tedious and hard to maintain.

This is where directives come in, instead of assigning the logic behind each user item in the controller you can define it in a directive:

app.directive('userItem', function() {
return {
    template: '<div>{{userData.name}} <button ng-click="like()">Like</button> <button ng-click="dislike()">Dislike</button>',
    scope: {
      userData: "="
    },
    link: function(scope, element, attrs) {
      scope.like = function(){
       scope.userData.like++;
      }

      scope.dislike = function(){
       scope.userData.like--;
      }
    }
}
});

In your html:

<div class="user_list>
   <user-item ng-repeat="user in users" user-data="user"></user-item>
</div>

By using the user-item directive you can now create a list of users anywhere in your application without having to redefine the logic that goes with each user. You'll notice that this also cleans up our html a bit and saves you on repeating code a lot. The directive wraps up your html and js into a reusable component.

EDIT: Regarding how we're passing the user data to the directive, this has to do with the isolate scope in directives which you can read about here. The basic idea is that it isolates the scope of the directive from the parent scope (allUsersController in our case), this is done to avoid unwanted clashes between the data in the 2 scopes and to promote re-usablity. But at the same time there is some data that we want the controller to share with the directive, so we "poke a hole" through the isolate scope to allow certain things in, which in our case is the userData defined in the directive scope.

You can visit the directives docs and scroll down to isolate scopes for more examples.

这篇关于angular js中的控制器和指令之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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