如何编写angularjs指令 [英] how to write a directive in angularjs

查看:140
本文介绍了如何编写angularjs指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢用指令进行自定义组件。我检查了很多的教程和其get困惑我任何人都可以解释一个指令是如何工作的。我刨,使组件

 <呼喊列表>< /呼喊列表>

有关喊列表中选择模板会是这样

 < D​​IV CLASS =喊NG-重复=呐喊呐喊>
    &所述p为H.; {{shout.message}}&下; / P>
    < IMG SRC =媒体/图像/ delete.pngWIDTH =32高度=32NG点击=deleteShout({{$指数}},{{shout._id}}')/ >
< / DIV>


解决方案

这是你的指令,一些行内注释:

angular.module('指令',[]).directive('shoutList',函数(){
  返回{
    限制:'E',//允许作为一种元素;缺省值是唯一的属性
    适用范围:{//创建一个分离范围
      喊:'='的喊声属性此范围内//映射变种
    },
    templateUrl:'模板/ shoutList.html',//加载模板文件
    控制器:函数($范围){
      //我们声明你的函数在视图使用
      $ scope.deleteShout =功能(IDX,ID){
        //做什么
      };
    }
  };
});

和模板文件:

< D​​IV CLASS =喊NG-重复=呐喊呐喊>
  &所述p为H.; {{shout.message}}&下; / P>
  < IMG SRC =媒体/图像/ delete.pngWIDTH =32高度=32
    NG-点击=deleteShout({{$指数}},{{shout._id}}')/>
< / DIV>

现在你可以用它在你的code,像这样:

控制器:

.controller('MainCtrl',函数($范围){
  $ scope.myShouts = // ...
});

查看:

<喊名单呼喊=myShouts>< /呼喊列表>

希望这有助于!

i like to make a custom component using directive. i checked lot of tutorials and its get confusing me can anyone explain how a directive works. the component i am planing to make is

<shout-list></shout-list>

the template for shout list will be like this

<div class="shout" ng-repeat="shout in shouts">
    <p>{{shout.message}}</p>
    <img src="media/images/delete.png" width="32" height="32" ng-click="deleteShout({{$index}},'{{shout._id}}')"/>
</div> 

解决方案

Here's your directive, with some inline comments:

angular.module( 'directives', [] ).directive( 'shoutList', function () {
  return {
    restrict: 'E', // allow as an element; the default is only an attribute
    scope: {       // create an isolate scope
      shouts: '='  // map the var in the shouts attribute to this scope
    },
    templateUrl: 'templates/shoutList.html', // load the template file
    controller: function ( $scope ) {
      // we declare a your function for use in the view
      $scope.deleteShout = function ( idx, id ) {
        // do whatever
      };
    }
  };
});

And the template file:

<div class="shout" ng-repeat="shout in shouts">
  <p>{{shout.message}}</p>
  <img src="media/images/delete.png" width="32" height="32" 
    ng-click="deleteShout({{$index}},'{{shout._id}}')" />
</div> 

And now you can use it in your code, like so:

Controller:

.controller( 'MainCtrl', function ( $scope ) {
  $scope.myShouts = // ...
});

View:

<shout-list shouts="myShouts"></shout-list>

Hope this helps!

这篇关于如何编写angularjs指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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