Ответ 1
Проблема заключается в том, что ваша функция компиляции не имеет доступа к области экземпляра элемента еще в момент компиляции.
Вы хотите, чтобы ng-click
выполнял метод области экземпляра, который еще не доступен при компиляции шаблона.
Я добавил комментарии к коду, чтобы проиллюстрировать, что происходит:
app.directive("fromCompile", function($compile) {
return {
restrict: 'E',
scope: {},
compile: function(tElement) {
// When AngularJS compiles the template element, it does not have
// access yet to the scope of the iElement, because the iElement does
// not exist yet.
// You want ng-click to execute a method of the iElement scope
// which does not exist here yet because you are modifying the
// template element, not the instance element.
// This will not give you the effect you are looking for because it
// will execute the function in a scope higher up the scope hierarchy.
tElement.append('<button ng-click=\"showAlert()\">Using compile: click me (this will not work correctly)</button>');
return {
post: function(scope, iElem, iAttrs) {
scope.showAlert = function() {
alert("This button was added using compile");
};
}
};
}
};
});
Чтобы решить проблему, вы можете либо использовать шаблон, чтобы AngularJS автоматически скомпилировал шаблон для вас:
app.directive("fromTemplate", function($compile) {
return {
restrict: 'E',
scope: {},
template: "<button ng-click=\"showAlert()\">Using template: click me (this will work)</button>",
link: function(scope, iElem, iAttrs) {
scope.showAlert = function() {
alert("This button was added using template");
};
}
};
});
Скомпилируйте шаблон вручную самостоятельно в функции ссылки экземпляра элемента (потому что вы можете получить доступ к правильной области там):
app.directive("fromLink", function($compile) {
return {
restrict: 'E',
scope: {},
link: function(scope, iElem, iAttrs) {
var linkFn = $compile("<button ng-click=\"showAlert()\">Using link: click me (this will work)</button>");
var button = linkFn(scope);
iElem.append(button);
scope.showAlert = function() {
alert("The button was added using $compile in link function");
};
}
};
});
Я создал Plunk со всем кодом и рабочими версиями прямо здесь.
Надеюсь, что это поможет!