1

so the question title is vague but basically I have a button element, I want to click that button and have another element be altered by it. Could anyone give me any idea's on what I'm missing or give me a clear example of how to achieve this.

code below:

html:

<div ng-controller="buttonController">
     <button ng-click="fadeIt()">click to fade</button>
     <div class="redbox" my-directive my-two-way-binding="twoWay">fade me</div>
</div>

controller:

function buttonController($scope){
    $scope.twoWay = false;

    $scope.fadeIt = function(){
        $scope.twoWay = !$scope.twoWay;
        console.log("inside fadeIt function $scope.twoWay is: " + $scope.twoWay);
    }
}

directive:

app.directive("myDirective", function(){
     return{
         restrict:"A",
         scope: {
             twoWayBind: "=myTwoWayBinding"
         },
         link:function(scope, element, attrs){
             //console.log("directive - twoWayBind is: " + scope.twoWayBind);    
             scope.$watch(scope.twoWayBind, function(newVal){
                 console.log('inside directive ' + scope.twoWayBind);    
             });
         }
     };
 });
0

1 Answer 1

3

scope.$watch(scope.twoWayBind should be scope.$watch('twoWayBind' because $watch accepts a string referring to a property on scope, not an actual model. Other than that I think you have the right idea.

Also, for cleanliness sake, you could have made it

scope:{
  twoWayBind: "=myDirective"
}

then you could shorten your template code to:

 <div class="redbox" my-directive="twoWay">

which in my opinion is a little cleaner.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.