vimal1083
vimal1083

Reputation: 8681

Access scope variable from directive?

I am a nerd in angular, creating a basic TODO app. In this i am trying to show delete when mouse enters in a li item which is render via todoListItem directive. I have other two more direcives mouseEnter and mouseLeave , from this mouseEnter how can i change todo.showDelete ?

angular.module('ToDo.directives', [])
    .directive('todoListItem', function() {
        return {
          restrict: 'E',
          template: "<li mouse-enter mouse-leave ng-repeat='todo in Todos | filter:searchText' class='todoList' ><input type='checkbox' ng-model='todo.done' /> <i ng-class=(todo.done) ? 'lineThrough' : ''>{{todo.text}}</i><a ng-show='todo.showDelete' >D</a></li>"
        };
    })
    .directive("mouseEnter", function () {
        return function (scope, element, attrs) {
            element.bind("mouseenter", function () {
                // how can i change `todo.showDelete` from here ?
            })
        }
    })
    .directive("mouseLeave", function () {
        return function (scope, element, attrs) {
            element.bind("mouseleave", function () {
                // how can i change `todo.showDelete` from here ?
            })
        }
    });

Upvotes: 0

Views: 96

Answers (1)

V31
V31

Reputation: 7666

You can make use of two way binding of Angular in directive and have something like this:

angular.module('ToDo.directives', [])
    .directive('todoListItem', function() {
        return {
          restrict: 'E',
          scope:{
             "todo":"="
          },
          template: "<li mouse-enter mouse-leave ng-repeat='todo in Todos | filter:searchText' class='todoList' ><input type='checkbox' ng-model='todo.done' /> <i ng-class=(todo.done) ? 'lineThrough' : ''>{{todo.text}}</i><a ng-show='todo.showDelete' >D</a></li>"
        };
    })
    .directive("mouseEnter", function () {
        return function (scope, element, attrs) {
            element.bind("mouseenter", function () {
                // how can i change `todo.showDelete` from here ?
            })
        }
    })
    .directive("mouseLeave", function () {
        return function (scope, element, attrs) {
            element.bind("mouseleave", function () {
                // how can i change `todo.showDelete` from here ?
            })
        }
    });

In HTML you need to have something like this:

<todo-list-item todo="todo"></todo-list-item>

Now you can change the todo variable of scope in directive which will reflect outside of directive as well.

Upvotes: 1

Related Questions