Je me demande comment faire pour que cet extrait de code fonctionne:
//html
<div ng-app="app">
<div ng-controller="AppCtrl">
<a my-dir ng-repeat="user in users">{{user.name}}</a>
</div>
</div>
//js
var app = angular.module('app', []);
app.controller("AppCtrl", function ($scope) {
$scope.users = [{name:'John',id:1},{name:'anonymous'}];
$scope.fxn = function() {
alert('It works');
};
})
app.directive("myDir", function ($compile) {
return {
link:function(scope,el){
el.attr('ng-click','fxn()');
//$compile(el)(scope); with this the script go mad
}
};
});
Je sais que c'est à propos de la phase de compilation mais je ne comprends pas le point, donc une courte explication serait très appréciée.
Réponses similaires:
Voici un plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview
app.directive("myDir", function($compile) {
return {
priority:1001, // compiles first
terminal:true, // prevent lower priority directives to compile after it
compile: function(el) {
el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
el.attr('ng-click', 'fxn()');
var fn = $compile(el);
return function(scope){
fn(scope);
};
}
};
});
ngClick
:Un dépliant: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview
app.directive("myDir", function($parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('fxn()');
return function (scope,Elm){
Elm.bind('click',function(){
exp(scope);
});
};
}
};
});
Vous pouvez essayer ceci:
<div ng-app="app">
<div ng-controller="AppCtrl">
<a my-dir ng-repeat="user in users" ng-click="fxn()">{{user.name}}</a>
</div>
</div>
<script>
var app = angular.module('app', []);
function AppCtrl($scope) {
$scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
$scope.fxn = function () {
alert('It works');
};
}
app.directive("myDir", function ($compile) {
return {
scope: {ngClick: '='}
};
});
</script>