0

trying to test a simple directive that will run if passed value is true but it works only once.

directive:

.directive('myDirective', function(){
        return {
            restrict: 'A',
            scope: {
               triggerObj: '@myDirective'
            },
            link: function (scope, elem, attrs) {
                scope.$watch('triggerObj', function() {
                    alert('success')
                });
            }
        };
    })

controller:

$scope.triggerObj = {};
$scope.triggerObj.trigger = false;

$scope.passValue = function(){
    //set to true
    $scope.triggerObj.trigger = true;
}

view:

<div my-directive='{[triggerObj.trigger]}'>
<button type='button' ng-click='passValue()'>click</button>

also tried to reset value to false before setting to true but still it works only once.

2
  • your triggerObj is not two way binding try instead of @triggerObj with =triggerObj Commented Jun 22, 2017 at 11:32
  • tried that in which case brackets needs to be removed from a view but the results remains the same Commented Jun 22, 2017 at 11:37

3 Answers 3

1

It works only ones, because passValue() function set $scope.triggerObj.trigger to true. And your $watch is working only when old value is not equal to new value, but you first change $scope.triggerObj.trigger from false to true, and all other times nothings change (you just trying to change $scope.triggerObj.trigger from true to true again).

To do the trick, try to upgrade the $scope.passValue function to this:

$scope.passValue = function() {
  if($scope.triggerObj.trigger) {
    $scope.triggerObj.trigger = false;
  } else {
    $scope.triggerObj.trigger = true;
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I tried to put $scope.triggerObj.trigger = false; before $scope.triggerObj.trigger = true; in the function but it does not work
@user1751287, because $scope.triggerObj.trigger = false works only ones, on controller load. Try to upgrade the $scope.passValue function as I wrote in my answer, this should help.
I put it within a function as well but still does not work...see edited answer
same result with your function as well
1

It works when you change passValue function like
http://jsfiddle.net/yjjysdzw/

  $scope.passValue = function() {
    $scope.triggerObj.trigger = !$scope.triggerObj.trigger;
  }

1 Comment

this works but I need directive to run only on true so if I pass true after your command I get the same result so it does not work
1

Two way data binding is achieved with '=', not '@'.

scope: {
  triggerObj: '=myDirective'
}

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.