angularjs – 如何使这个自定义指令更好?
我正在尝试为计数器小部件实现自定义指令.
我已经能够实现它,但有许多事情我需要一些亮点. >这个指令能以更好的方式编写吗? HTML片段 <body> <counter-widget startnumber=1 ></counter-widget> <counter-widget startnumber=1 ></counter-widget> <counter-widget startnumber=1 ></counter-widget> </body> JS片段 angular.module("myApp",[]) .directive("counterWidget",function(){ return{ restrict:"E",scope:{ },link:function(scope,elem,attr){ scope.f = attr.startnumber; scope.add = function(){ scope.f = Number(scope.f) + 1; } scope.remove = function(){ scope.f =Number(scope.f) - 1; } scope.reset = function(){ scope.f = 1; } },template:"<button ng-click='add()'>more</button>"+ "{{f}}"+ "<button ng-click='remove()'>less</button> "+ "<button ng-click='reset()'>reset</button><br><br>" } }) 在此先感谢您的帮助. 解决方法
首先,传入你的startnumber属性,这样我们就可以重置为那个数字,而不是硬编码.
如果要使用多个计数器,则需要隔离范围. app.directive("counterWidget",scope:{ startnumber: '=',resetter: '=' },attr){ scope.f = attr.startnumber; scope.add = function(){ scope.f++ } scope.remove = function(){ scope.f-- } scope.reset = function(){ scope.f = attr.startnumber scope.$parent.triggerReset() } scope.$watch(function(attr) { return attr.resetter },function(newVal) { if (newVal === true) { scope.f = attr.startnumber; } }) },template:"<button ng-click='add()'>more</button>"+ "{{f}}"+ "<button ng-click='remove()'>less</button> "+ "<button ng-click='reset()'>reset</button><br><br>" } }) 在控制器中,您只需添加一个小的重置功能,每个指令都在观察: $scope.triggerReset = function () { $scope.reset = true; console.log('reset') $timeout(function() { $scope.reset = false; },100) } 我不会过度复杂的减量和增量函数. – 应该没事. 我们通过添加属性并将其传递给指令来创建全局重置功能.然后,我们将该属性视为真正的价值.每当我们点击重置时,我们在$parent范围内触发一个函数(triggerReset()函数).该函数快速切换$scope.reset值.任何在其resetter属性中具有该绑定的指令都将重置为startnumber属性中的任何内容. 另一个好处是重置只会影响你想要的计数器.您甚至可以创建多组计数器,这些计数器仅重置其自己的组中的计数器.您只需要为每个要自己重置的组添加触发器功能和变量. Plunker 编辑: 所以问题出现在评论中 – $watch函数’错过’切换? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |