我最近将carreer从后端更改为前端开发人员,现在正在学习angularJs。
我有以下设置:我创建了一个按钮组件,根据给定的属性返回链接或按钮。我想知道如果我通过课堂会发生什么。这给了我一些不需要的行为,因为组件通过但也保留了它。
成分:
(function() {
'use strict';
angular
.module('myApp')
.component('euButton', {
template: function ($element, $attrs) {
if($attrs.click){
return `
<button onClick="${$attrs.click}" class="${$attrs.class}">
<ng-transclude>
</ng-transclude>
</button> `
}
if($attrs.href){
return `
<a href="${$attrs.href}" class="${$attrs.class}">
<ng-transclude>
</ng-transclude>
</a>`
}
},
transclude: true,
bindings: {
click: '&',
href: '@',
}
})
})();
我创建我的组件,如下所示:
<eu-button href="http://www.google.be" class="btn btn-default">Link example</eu-button>
<br>
<eu-button click="console.log('You have clicked me')" class="btn btn-default">Button example</eu-button>
以下视图是我所期望的,但不是我想要达到的目标。我的按钮似乎包含同一类的2个实现,我不希望发生这种情况。
我在这个例子中使用了bootstrap类。理想情况下,我会通过自己的课程发送。
有关如何实现这一目标的任何帮助?
答案 0 :(得分:1)
您可以根据属性使用模板生成。
jsfiddle上的实例。
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.log = function() {
console.log('You have clicked me')
}
})
.directive('euButton', function() {
return {
restrict: "E",
transclude: true,
template: ['<a ng-if="isHref" href="{{href}}" class="{{class}}"><ng-transclude></ng-transclude></a>',
'<button ng-if="!isHref" ng-click="click()" class="{{class}}"><ng-transclude></ng-transclude></button>'
].join(""),
scope: {
click: "&",
href: "@",
class: "@"
},
link: function(scope, elem, attr) {
if (attr.href) {
scope.isHref = true;
}
}
};
});
&#13;
.error {
color: red;
font-style: italic;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<eu-button href="http://www.google.be" class="btn btn-default error">Link example</eu-button>
<br>
<eu-button click="log()" class="btn btn-default">Button example</eu-button>
</div>
</div>
&#13;