如何写在angularjs一个指令(how to write a directive in angu

2019-07-19 01:14发布

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

<shout-list></shout-list>

对于喊列表中选择模板会是这样

<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> 

Answer 1:

这是你的指令,与一些在线评论:

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
      };
    }
  };
});

和模板文件:

<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> 

现在你可以在你的代码中使用它,就像这样:

控制器:

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

视图:

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

希望这可以帮助!



文章来源: how to write a directive in angularjs