javascript - Angular custom directive - two way binding which always sets attribute to true or false -


i'm creating custom angular directive slide in menu needs watch couple of attributes , 1 of attributes needs 2 way bound main controller scope (sometimes). however, attribute not added developer needs added automatically , set default (false). so, directive can used this.

<slide-menu position="right" is-open="menuisopen"></slide-menu> 

or this:

<slide-menu></slide-menu> 

when used first way main controller able open , close menu changing value of boolean $scope.menuisopen.

when used without supplying is-open attribute should default false , used internally , child toggle directive.

an additional complication whether attribute supplied developer or not should exist in dom. in second example above directive set false default , add attribute is-open="false" dom?

the reason requiring is-open="false/true" in dom @ times menu operated using css tansitions use following selector:

slide-menu[is-active="true"]{     // slide menu in using transforms/transitions } 

there jsfiddle here shows how far have got.

http://jsfiddle.net/jonhobbs/gepve/

obviously doesn't work, shows how have tried set default , how have tried use @ , & on isolated scope 1 time binding (the menu position) , 2 way bound expression is-open variable.

i'm long way achieving need advice appreciated.

have @ fiddle http://jsfiddle.net/gepve/38/ took 1 started , updated act specified.

you can make 2 way binding value optional adding ? on scope definition.

like

{     scope: {         'isopen':'=?'     } } 

now is-open attribute optional. can set default value in directive controller, had started do.

next, in order synchronize dom attribute scope value can use $watch.

$scope.$watch('isopen', function(val) {     $element.attr('is-open', val); }); 

finally, changed second 'slidemenutoggle' directive wrap/transclude element in order add ng-click handler. avoid nastiness calling $scope.$apply yourself.

let me know if works you.


edit

answering question in comment, can pass value directly without having bound scope, need wrap value in quotes.

for example

<div ng-controller='ctrl'>   <hello world='imonscope'></hello> </div> 

assuming 'hello' directive scope of 'world': '=?' angular assign reference parent scope's 'imonscope' object directive's $scope.world member, allowing 2 way binding scenario.

to provide value directly may this

<div ng-controller="ctrl">     <hello world="'directvalue'"></hello> </div> 

in scenario angular assign 'directvalue' directive's $scope.world member.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -