如何在 angularjs 中编写指令 [英] how to write a directive in angularjs
本文介绍了如何在 angularjs 中编写指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢使用指令制作自定义组件.我检查了很多教程,它让我感到困惑,任何人都可以解释指令的工作原理.我打算制作的组件是
呼喊列表的模板是这样的
<p>{{shout.message}}</p><img src="media/images/delete.png" width="32" height="32" ng-click="deleteShout({{$index}},'{{shout._id}}')"/>
解决方案
这是您的指令,带有一些内嵌注释:
angular.module( 'directives', [] ).directive( 'shoutList', function () {返回 {限制:'E',//允许作为一个元素;默认值只是一个属性scope: {//创建一个隔离作用域Shouts: '='//将shouts 属性中的var 映射到这个范围},templateUrl: 'templates/shoutList.html',//加载模板文件控制器:函数($scope){//我们声明一个你的函数以在视图中使用$scope.deleteShout = 函数(idx,id){//做任何事};}};});
和模板文件:
<p>{{shout.message}}</p><img src="media/images/delete.png" width="32" height="32"ng-click="deleteShout({{$index}},'{{shout._id}}')"/>
现在你可以在你的代码中使用它,就像这样:
控制器:
.controller( 'MainCtrl', function ( $scope ) {$scope.myShouts =//...});
查看:
</shout-list>
希望这会有所帮助!
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屋!
查看全文