0
votes

I try to update variable's value from the directive, but it is stiil undefined when I use it in a function.

Directive:

link: function (scope, elem, attrs) {
    elem.bind('click', function () {
        scope.$apply(function () {
            scope.UserName = elem.html();
        });

        scope.$apply("MyFunc()");
    });
}

Controller:

$scope.MyFunc = function myfunction() {
    OrderService.ServiceFunc($scope.UserName, $scope.Param2).success(
    function (data) {
        $scope.MyData= data;
    });
}

In the controller $scope.UserName is undefined.

I tried use the scope.$apply() (in several variations) - didn't help. Also "scope.$apply("MyFunc()");" executes functions that is defined in the controller's scope, but for some reason I doesn't affect my scope variable.

when I added $watch on this variable + alert - the only time it alerted was only at the beginning when it was undefined, although the debug showed that the code reaches the line when the value was supposed to change in the directive (the $watch didn't alert that moment)

Thank You.

1
Html template have UserName model property? - user3559224
No. I want to update $scope.Username in the controller so It could execute a function with this variable. I don't need it in the html template. - Lichte
use $rootScope instead of $scope - user3559224

1 Answers

0
votes

you can hook up your directive to a function via an attribute.

have a look at this example, add a directive with $apply button structure http://plnkr.co/edit/ZrSkaT0yuB4UWKH8h2Mn?p=preview

you basically create an attribute in your directive, bind that to the function and then basically apply that with a click bind.