AngularJS: Cannot get my directive working -
i'm in second day of learning angularjs , have simple example of how change dom on user's action, somehow not work me. here examlple:
html file:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../scripts/angular.min.js"></script> <script src="../scripts/controllers/app.js"></script> <script src="../scripts/jquery-1.4.1.min.js"></script> </head> <body ng-app="myapp"> <my-widget> <p>hello world</p> </my-widget> </body> </html>
file directive's action:
var app = angular.module('myapp', []); app.directive("my-widget", function () { var linkfunction = function (scope, element, attributes) { var paragraph = element.children()[0]; $(paragraph).on("click", function () { $(this).css({ "background-color": "red" }); }); }; return { restrict: "e", link: linkfunction }; });
nothing happens when clicking on paragraph. cannot find why.
simply change directive name camelcasing, angular translate my-widget
. in addition, jquery $
alias not available , shouldn't used angular. have element, interact directly, using element.css()
change css properties.
in addition, based on comments below, makes more sense change restrict either "a" or "ea" , apply directive directly element intend change.
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../scripts/angular.min.js"></script> <script src="../scripts/controllers/app.js"></script> </head> <body ng-app="myapp"> <div my-widget style="width: 300px; height: 200px; background-color: orange;"> <p>hello world</p> </div> </body> </html>
this saves needing traverse child elements.
app.directive("mywidget", function () { var linkfunction = function (scope, element, attributes) { element.on("click", function () { element.css("background-color", "red"); }); }; return { restrict: "ea", link: linkfunction }; });
see working plunker.
per documentation:
angular normalizes element's tag , attribute name determine elements match directives. typically refer directives case-sensitive camelcase normalized name (e.g. ngmodel). however, since html case-insensitive, refer directives in dom lower-case forms, typically using dash-delimited attributes on dom elements (e.g. ng-model).
the normalization process follows:
strip x- , data- front of element/attributes. convert :, -, or _-delimited name camelcase.
Comments
Post a Comment