0

Whats the best way to assign a new value through a directive? A two way databinding.

I have a fiddle here where i tried. http://jsfiddle.net/user1572526/grLfD/2/ . But it dosen't work.

My directive:

myApp.directive('highlighter', function () {
    return {
        restrict: 'A',
        replace: true,
               scope: {
                    activeInput: '='
                },
        link: function (scope, element, attrs) {
            element.bind('click', function () {
                scope.activeInput = attrs.setInput 
            })
        }
    }
});

And my controller:

function MyCtrl($scope) {
             $scope.active = {
                value : true
            };
}

And my view:

<h1 highlighter active-input="active.value" set-input="false">Click me to update Value in scope: {{active}}</h1>

So what i wanna do is update the scope.active with the given attribute setInput.

Any ideas what I'm doing wrong here?

Joe
  • 4,274
  • 32
  • 95
  • 175
  • possible duplicate of [Using scope.$watch and scope.$apply](http://stackoverflow.com/questions/15112584/using-scope-watch-and-scope-apply) – Stewie Jan 10 '14 at 14:31

1 Answers1

2

With element.bind you leave the realm of Angular, so you need to tell Angular that something had happened. You do that with the scope.$apply function:

scope.$apply(function(){
  scope.activeInput = attrs.setInput;
});

here is an updated jsfiddle.

Stewie
  • 60,366
  • 20
  • 146
  • 113
  • :), had the link in the clipboard when your answer appeared! – Davin Tryon Jan 10 '14 at 14:34
  • @DavinTryon I figured it was a race. Still a very nice gesture from you, to update my answer with an example. But eventually, question will probably be closed as dupe anyway. :) – Stewie Jan 10 '14 at 14:40