0

Here is my directive:

function ajaxMessageData()
{
    var ajaxMessage = {
        link: link,
        restrict: "EA",
        template: "success",
        scope: {
            success: '='
        }
    };

    return ajaxMessage;

    function link(scope, elm, attrs)
    {

            console.log(scope.success);
            scope.$watch(attrs.success, function (newValue) {
                console.log("Changed to " + newValue);
            });

    }
}

and in html:

<ajax-message success="vm.message"></ajax-message>

Problem is with scope inside directive I get initial message from vm.message (it is my controller var) but when my vm.message change it not detectd in directive... Also I would like to template show only if I get success message from vm.success. Anyone know how to accomplish this? Thanks

1
  • Try scope.$apply() Commented Feb 11, 2016 at 15:05

1 Answer 1

5
  1. You're passing the wrong argument to the $watch. It should be an expression -- not the value of the attrs object.
  2. You can use the ng-if directive to control visibility.
  3. Not sure if this is intended, but the success template maybe needs a curly binding: "{{ success }}"

Example:

myApp.directive('ajaxMessage', function() {

  return {
    restrict: 'EA',
    scope: {
      success: '='
    },

    // Use anything you like in the template -- note the ng-if will only
    // render the element when the success property has a value
    // Also note the {{ binding }}

    template: "<div ng-if=\"success\" class=\"alert alert-info\">{{ success }}</div>",

    link: function($scope, $element, $attrs) {

      // Watching $scope.success (not the $attrs.success)

      $scope.$watch('success', function(value) {
        console.log('Success is now:', value);  
      });
    }
  };

});

... or see this plunker in action.

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.