1

Hi I have some nested menu where I am trying to change the color of a child scope from parent but its not working. Here is the simplified code.

.directive('botMenuClick', function() {
    return {
        link: function(scope,ele,attrs){
            ele.bind('click', function(){
                 if(ele.attr('homeBtn')==='true'){
                    scope.$parent.setDisplay = {'color': '#fff'} // this applies to all children but not the one which is set in else condition
                 }else{
                     scope.setDisplay = {'color': 'green'}
                 }
                 scope.$apply();
            }); 
        }
    }
})

So, once I get in to the else condition and that menu color is changed to green then no matter what it won't change to white even if I go in the above homeBtn condition.

alflashy
  • 81
  • 1
  • 10

1 Answers1

2

That's because that's how prototypal inheritance works. If a child object sets a property with the same name as a property on a prototype then the child is actually creating a new property in itself which hides the parent property. From this mdn article:

"Setting a property to an object creates an own property. The only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter."

My assumption is that the UI element is binding to the child scope property, which doesn't exist until it is set by the else condition, so up until that point it's looking up the prototype chain for the value of setDisplay. As soon as the else condition fires setDisplay gets set on the child scope, hiding the prototype value for the rest of eternity.

bmceldowney
  • 2,307
  • 13
  • 19
  • but setDisplay is already set in html in ng-style like this
    {{bottomSubMenu.subMenuLabel}}
    – alflashy Sep 06 '14 at 15:10
  • Binding to a scope value in HTML is not setting anything. Setting an HTML binding lets the `$compile` service know which JavaScript properties on the `scope` to bind to. All declaration and modification of properties happens in JavaScript. – bmceldowney Sep 06 '14 at 17:02
  • Please read this question to get more context: http://stackoverflow.com/questions/16972976/angular-js-propagate-child-scope-variable-changes-to-parent-scope?rq=1 – bmceldowney Sep 06 '14 at 17:20
  • I got the Plunker link. There are two menus the first one works but I want the menu 1 to close all menu. I tried the second approach so that I can detect the menu 1 and perform other task but one I modifying scope I can't change the it again from parent. here is the link http://plnkr.co/edit/vBnXZNIc8aEizpGxXhhK?p=preview – alflashy Sep 06 '14 at 21:08