Saturday 15 June 2013

javascript - Rewriting directives to not use isolate scope? -



javascript - Rewriting directives to not use isolate scope? -

i have 2 simple directives want apply element.

this directive gives focus particular element when status changes true:

.directive('focusoncondition', function ($timeout) { homecoming { restrict: 'a', scope: { condition: '=focusoncondition', }, link: function (scope, el, attr) { scope.$watch('condition', function (value) { if (value) { $timeout(function () { el[0].focus(); }); } }); } }; });

this directive calls function when user presses 'enter':

.directive('triggeronenter', function () { homecoming { restrict: "a", scope: { func: '&triggeronenter' }, link: function (scope, el, attr) { $(el).keypress(function (event) { if (event.which == 13) scope.func(); }); } }; })

these 2 directives work separately, don't work if seek apply them same element. example:

<form ng-show="pastingresults"> <textarea placeholder="paste results , press 'enter'" ng-model="pastedresultdata" trigger-on-enter="pasteresults()" focus-on-condition="pastingresults"></textarea> <button type="submit" ng-click="pasteresults()">submit</button> </form>

result in error, [$compile:multidir] multiple directives (...) on (...).

how can resolve this? new angular js, , 'put in isolated scope' thing know how when making directives. assume must possible implement these without using isolated scope, don't know how.

can give example?

if remove isolated scopes, can access options looking @ attributes on element straight using attrs object passed linking function, $eval evaluate if needs be:

app.directive('focusoncondition', function ($timeout) { homecoming { restrict: 'a', link: function (scope, el, attr) { scope.$watch(attr.focusoncondition, function (value) { if (value) { $timeout(function () { el[0].focus(); }); } }); } }; });

and

app.directive('triggeronenter', function () { homecoming { restrict: "a", link: function (scope, el, attr) { $(el).keypress(function (event) { if (event.which == 13) { scope.$eval(attr.triggeronenter); } }); } }; });

these can seen working @ http://plnkr.co/edit/1iobnvlmrxm8hgrrobbd?p=preview

javascript angularjs angularjs-directive

No comments:

Post a Comment