eded
eded

Reputation: 3948

Call the function in parent scope within a directive does not update parent scope

I tried to call the function in parent scope within a directive link function to update the one of parent scope attributes.

var app = angular.module('myApp', []);

app.controller('MyCtrl', function($scope) {
    var users = [{
        name: 'Andy',
        age: 9
    },{
        name: 'Tom',
        age: 10
    },{
        name: 'Jerry',
        age: 11
    },{
        name: 'Harry',
        age: 12
    }];

    $scope.users = users;
    $scope.currentUser = users[0];
    $scope.updateCurrentUser = function(index) {
        $scope.currentUser = users[index];
    };
});

app.directive('myDirective', function() {
    return {
        template: '<div><button ng-repeat="user in users">{{ user.name }}</button></div>',
        restrict: 'EA',
        link: function(scope, element, attrs) {
            element.on('click', 'button', function() {
                scope.updateCurrentUser($(this).index());
            });
        }
    };
});

source code

Suppose I click any button, the currentUser should display the update corresponding user data. however, looks like it does not work. I wonder why and how to fix this issue?

Upvotes: 0

Views: 90

Answers (2)

Josep
Josep

Reputation: 13071

You don't need to use a jQuery event, you can just use the ngClick directive, your code will be much cleaner and angularjs friendly:

Change your directive, make it like this:

app.directive('myDirective', function() {
  return {
    template: '<div><button ng-click="updateCurrentUser($index)" ng-repeat="user in users">{{ user.name }}</button></div>',
    restrict: 'EA'
  };
});

Working example

Upvotes: 2

Davin Tryon
Davin Tryon

Reputation: 67296

Because the click event is handled without Angular's knowledge, you need to $apply your changes:

element.on('click', 'button', function() {   
    scope.updateCurrentUser($(this).index());
    scope.$apply();
});

$apply runs and Angular $digest. The $digest will take care of two-way binding in the parent.

Upvotes: 2

Related Questions