ng-click 在我的指令中不起作用
ng-click not working in my directive
我这里的场景很简单。
<body>
<h1 nametag name="name" logsomthing="logsomthing()">Hello {{name}} <a href="#" ng-click="logsomthing()">Click here for alert</a></h1>
</body>
js
angular.module('test', [])
.directive('nametag', function() {
return {
scope: {
name: '=',
logsomthing: '&'
},
controller: function($scope, $attrs, $log) {
$scope.name = 'John Doe';
$scope.logsomthing = function() {
alert('it is working');
}
},
link: function(scope, elem, attrs) {
}
};
});
它应该在点击时发出警报('it is working'),但没有任何反应。我找不到解决方案。
如果你想让它工作,你需要在你的指令中放置一个模板:
http://plnkr.co/edit/QXnDqDwQuyGhKpHZoCvy?p=preview
指令:
angular.module('test', [])
.directive('nametag', function() {
return {
scope: {
name: '@',
},
template:'Hello {{name}} <a href="#" ng-click="logsomthing()">Click here for alert</a>',
controller: function($scope, $attrs, $log) {
//$scope.name = 'John Doe'; // Not necessary anymore, sent by the view
$scope.logsomthing = function() {
alert('it is working');
}
},
link: function(scope, elem, attrs) {
}
};
});
查看:
<body>
<h1 nametag name="John Doe"></h1>
</body>
而且你也不需要定义函数 logsomthing 的 3 次
我这里的场景很简单。
<body>
<h1 nametag name="name" logsomthing="logsomthing()">Hello {{name}} <a href="#" ng-click="logsomthing()">Click here for alert</a></h1>
</body>
js
angular.module('test', [])
.directive('nametag', function() {
return {
scope: {
name: '=',
logsomthing: '&'
},
controller: function($scope, $attrs, $log) {
$scope.name = 'John Doe';
$scope.logsomthing = function() {
alert('it is working');
}
},
link: function(scope, elem, attrs) {
}
};
});
它应该在点击时发出警报('it is working'),但没有任何反应。我找不到解决方案。
如果你想让它工作,你需要在你的指令中放置一个模板:
http://plnkr.co/edit/QXnDqDwQuyGhKpHZoCvy?p=preview
指令:
angular.module('test', [])
.directive('nametag', function() {
return {
scope: {
name: '@',
},
template:'Hello {{name}} <a href="#" ng-click="logsomthing()">Click here for alert</a>',
controller: function($scope, $attrs, $log) {
//$scope.name = 'John Doe'; // Not necessary anymore, sent by the view
$scope.logsomthing = function() {
alert('it is working');
}
},
link: function(scope, elem, attrs) {
}
};
});
查看:
<body>
<h1 nametag name="John Doe"></h1>
</body>
而且你也不需要定义函数 logsomthing 的 3 次