gpt4 book ai didi

angularjs - 如何在angularjs中编写指令

转载 作者:行者123 更新时间:2023-12-04 03:16:12 28 4
gpt4 key购买 nike

我喜欢使用指令制作自定义组件。我检查了很多教程,它使我感到困惑,任何人都可以解释指令的工作原理。我打算制造的组件是

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

最佳答案

这是您的指令,并带有一些内联注释:

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 :

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

看法:

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

希望这可以帮助!

关于angularjs - 如何在angularjs中编写指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14620521/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com