我想知道如何指定何时应该调用指令的链接函数。
目前我有以下代码:
<my-directive username="abc"></my-directive>
&#13;
module.directive("myDirective", [{
restrict: "A",
link($scope, element, others) {
//if element.clicked() {
// console.log("you clicked me");
//}
}
}]);
&#13;
正如你所看到的,我已经注释了我想要做的伪代码,并且我已经看到它可以做像element.onClick = function(){}这样的事情。但是当单击该元素时,似乎仍然没有调用它。
由于
答案 0 :(得分:2)
答案 1 :(得分:0)
试试这个
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.abc = 'abc';
});
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
username: '='
},
link:link,
template: '<div>Click Here</div>'
};
function link(scope,elem,others){
elem.bind('click', function() {
console.log('on click');
});
}
});
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js" data-require="angular.js@1.4.x"></script>
<script src="app.js"></script>
</head>
<body ng-app="plunker" ng-controller="MainCtrl">
<my-directive username="abc"></my-directive>
</body>
答案 2 :(得分:0)
你也可以这样试试!
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.abc = 'abc';
});
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
username: '='
},
link:link,
template: '<div ng-click="click()">Click Here</div>'
};
function link(scope,elem,others){
scope.click = function() {
console.log('on click', scope.username);
}
}
});
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js" data-require="angular.js@1.4.x"></script>
<script src="app.js"></script>
</head>
<body ng-app="plunker" ng-controller="MainCtrl">
<my-directive username="abc"></my-directive>
</body>