Last active
August 29, 2015 13:57
-
-
Save ryanemmm/9424554 to your computer and use it in GitHub Desktop.
angular directive data binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
I have a directive (errorhandler, see below) that is restricted to Element and Attribute | |
Currently, I've got two separate two way bindings, and two separate watchers: | |
one for the element case, one for the attribute case | |
** Is there a way to conditionally set the directives isolate scope? | |
scope : { | |
errors : "=????" //use errorhandler value if available, else use @error value | |
} | |
Instead of: | |
scope : { | |
case1 : "=errorhandler" #the Element case | |
, case2 : "=errors" #the Attribute case | |
} | |
I'd like to do something like: | |
scope : { | |
errors : "=errorhandler || errors" #look for errorhandler else 'fall back' to looking for attr.errors | |
} | |
*/ | |
#case1 | |
input(type="text", ng-model="some.thing", errorhandler="some.$errors.thing") | |
#case2 | |
div.someothercontrol | |
errorhandler(errors="some.$errors.otherthing") | |
# directive | |
angular.module('myapp', []) | |
.directive('errorhanlder', function () { | |
use strict'; | |
return { | |
restrict: "EA" | |
, replace: true | |
, transclude: true | |
, scope : { | |
tag : "=ofpErrors" | |
, prop : "=errors" | |
} | |
, link : function(scope, el, attrs){ | |
var errbox = $compile('<ul class="ofp-errors" ng-show="errors"></ul>')(scope) | |
, handler = function(newerrors, olderrors){ | |
scope.errors = newerrors; | |
if(!newerrors) return; | |
var error_lis = '<li ng-repeat="err in errors">{{ err }}</li>'; | |
$compile(errbox.html(error_lis))(scope); | |
}; | |
//handle the case where the directive is invoked... | |
if(el[0].tagName.toLowerCase() === 'ofp-errors'){ | |
//... from a tag | |
el.replaceWith(errbox) | |
scope.$watchCollection('prop', handler); | |
} else { | |
//... from an attribute | |
el.after(errbox); | |
scope.$watchCollection('tag', handler); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment