angular.element("<my-directive></my-directive>")
Dlaczego nie mogę po prostu podać nazwy mojej dyrektywy? Wydaje się tak dziwne napisać wiersz HTML wewnątrz js ...
Czy jest jakiś lepszy sposób na stworzenie instancji dyrektywy w pamięci?
Odpowiedzi:
0 dla odpowiedzi № 1Wspólny wzór pisania dyrektyw jest taki.
angular.module("myApp.directives", ["myApp.services"])
/*
toggleclass
A generic directive for toggling a class directly on an element
or by specifying a toggle-target option
eg. toggleclass="{class: "open", target=".element"}"
*/
.directive("toggleclass", function(){
return {
restrict: "A",
link: function(scope, element, attrs){
element.on("click", function(){
var ops = scope.$eval(attrs.toggleclass);
// If a toggle-target is set
if(ops.target){
element = angular.element(document.querySelector(ops.target));
}
// Toggle the class
element.toggleClass(ops.class);
});
}
}
});
});
0 dla odpowiedzi nr 2
angular.element("<my-directive></my-directive>")
AFAIK ten fragment kodu naprawdę nie tworzy dyrektywy, po prostu tworzy element oznaczony "moja-dyrektywa".
Nie potrzebujesz przy okazji znacznika zamykającego. angular.element("<my-directive>")
jest ważny.
Jeśli chcesz uzyskać pełną informację: angular.element(document.createElement("my-directive"))
.
To jest coś w rodzaju jQuery światło.
aby wprowadzić dyrektywę, musisz skompilować trochę DOM i przekazać zakres.
var e = angular.element("<my-directive></my-directive>");
$compile(e)($scope);