@H_403_2@
我正在尝试为计数器小部件实现自定义指令.
我已经能够实现它,但有许多事情我需要一些亮点.
>这个指令能以更好的方式编写吗?
>我如何以更好的方式使用范围:(隔离范围)?
>点击任何重置按钮我希望所有的startnumber都重置为“1”?
>范围从何处继承?是否继承自被调用的元素?
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属性中的任何内容.
另一个好处是重置只会影响你想要的计数器.您甚至可以创建多组计数器,这些计数器仅重置其自己的组中的计数器.您只需要为每个要自己重置的组添加触发器功能和变量.
这是演示:
编辑:
所以问题出现在评论中 – $watch函数’错过’切换?
我做了一些测试,到目前为止我得到的最佳答案是,如果我将它设置为1ms甚至完全删除时间参数,那么$watch仍会触发.
我也在这里向社区提出这个问题:Can $watch ‘miss’?
@H_403_2@