Как написать директиву в angularjs
Я хотел бы сделать пользовательский компонент, используя директиву. Я проверил много учебников, и это сбивает меня с толку. Может кто-нибудь объяснить, как работает директива. компонент, который я планирую сделать,
<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>
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>
Надеюсь это поможет!