将按钮转换为指令AngularJS

时间:2018-02-24 12:25:29

标签: javascript html angularjs angularjs-directive

正如标题所说,我想将HTML页面上的按钮称为自定义指令。喜欢:

<buy-button></buy-button>

以下是我要转换的代码:

<md-button class="md-cornered" 
           ng-disabled="0>=gains" 
           ng-click="buyTaxi()">Buy a Taxi</md-button>

1 个答案:

答案 0 :(得分:1)

这是元素到指令的基本转换。这样做没有真正的优势,但它可以满足您的需求:

<强>&GT; demo fiddle

视图

<div ng-controller="MyCtrl">
  <my-directive></my-directive>
</div>

AngularJS应用程序

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {});

myApp.directive('myDirective', function () {
    return {
      restrict: 'E',
      replace: true,
      template: `<md-button class="md-cornered" ng-disabled="0>=gains" ng-click="buyTaxi()">Buy a Taxi</md-button>`,
      link: function (scope, element, attrs) {

         scope.gains = 1;

         scope.buyTaxi = function () {
            console.log('Buy me a nice taxi!');
         }
      }
    }
});