可重复使用的按钮指令不起作用

Reusable button directive not working

本文关键字:按钮 指令 不起作用      更新时间:2023-09-26

Hi可重复使用按钮指令不起作用,

这里我创建了可重复使用的按钮指令,在下面的代码中,静态按钮可以工作,但动态(指令)按钮不工作。请检查下面的代码

感谢您的帮助

var app = angular.module('testApp', [ ]);
  
app.directive('telSavebutton', function() {
  return{
      restrict: 'E',
      template: '<button type="submit" ng-click="testcontroller()" >directive button</button>',
      transclude: true,
      scope: {
          onSubmit: '&',
          likeClick: '&'			 
      },
      link: function(scope, element, attributes){
          scope.submit = function(){
              scope.onSubmit();
          }
      }
  }
});  
   
app.controller('testCntler', ['$scope', '$location',  function ($scope, $location) {
  $scope.testcontroller=function()
  {
	   alert("Working")
  }
}]);
<script data-require="angular.js@~1.3.15" data-semver="1.3.15"
        src="https://code.angularjs.org/1.3.15/angular.js"></script>
<body class="hold-transition skin-blue sidebar-mini" data-ng-app="testApp"  > 
<form novalidate="novalidate" ng-submit="vm.onSubmit()"
      ng-controller="testCntler" >
    
    <table width="293" border="0">
      <tr>
        <td width="127">First Name</td>
        <td width="150"> <input type="text"  ng-model="fname" ></td>
      </tr>
      <tr>
        <td>Mid Name</td>
        <td> <input type="text"  ng-model="mName" ></td>
      </tr>
      <tr>
        <td>Last Name</td>
        <td> <input type="text"  ng-model="lName" ></td>
      </tr>
      
      <tr>
        <td colspan="2"> <button type="submit"
            ng-click="testcontroller()" >Static button</button> 
        <tel-Savebutton   check-Id="firstName" ></tel-Savebutton></td>
       </tr>    
    </table>   
</form>
</body>

您的问题是telSavebutton指令具有隔离作用域,但您在该指令的模板中使用了函数testcontroller(),该函数在Controller的作用域中。

通过首先修改你的模板来修复它:

template: '<button type="submit" ng-click="submit()" >directive button</button>',

通过传递一个函数作为指令实例的属性:

<tel-savebutton on-submit="testcontroller"></tel-savebutton></td>

更改指令中的ng-click="testcontroller()":

template: '<button type="submit" ng-click="onFormSubmit()" >directive button</button>'

并在html:中添加提交

<tel-Savebutton check-Id="firstName" on-form-submit="testcontroller()"></tel-Savebutton></td>

同时更改范围参考:

scope: {
        onFormSubmit: '&'        
    },