Trong Lam Phan
Trong Lam Phan

Reputation: 2412

How can i use scope's variable in directive?

I want to get a scope's variable in directive as a javascript variable. Here is my code:

app.controller("Home", ["$scope", function($scope) {
    ...
    $scope.nb_msg = data.length;
    ...
}]);

app.directive("myDiv", function() {
    // Here, i want to get $scope.nb_msg
    var nb_msg = ???;
    var result = [];
    // do something with nb_msg to get result
    var template = "";
    ...
    for(var i=0; i<10; i++) {
        template += "<span>" + result[i] + "</span>";
    }
    ...

    return {
        restrict: "E",
        template: template
    };
});

How can i do? Thanks in advance!

Upvotes: 0

Views: 242

Answers (2)

Michael Kang
Michael Kang

Reputation: 52847

You can access scope in your link function:

app.directive("myDiv", function() {    
    return {
        restrict: "E",
        template: '<span ng-repeat="i in result">{{i}}</span>',
        link: function(scope, element, attr) {

             // Here, i want to get $scope.nb_msg
             var nb_msg = scope.nb_msg;
             scope.result = [];
             for(var i=0; i<10; i++) {
                 scope.result.push(i);
             }


        }
    };
});

Upvotes: 2

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

if your directive doesn't create an isolated scope the variables will be available inside the directives controller, compile and link functions.

if your directive does create an isolated scope you can't, not like that, directives are not aware of outide controllers so they can't access controllers variables, you do have other choices

1st -- use the controller variable as an attribute value for the directive and linked it using '=' in your scope if you want to provide 2 way binding;

2nd -- put the variables to share inside a service and inject it into both the controller and the directive.

3rd --(less recommended) use scope.$parent to access the controllers scope, this approach always assumes that your directive will always be contained inside that controller.

Note. in any case you will have the variables available in the directives definition function

Upvotes: 0

Related Questions