James Heald
James Heald

Reputation: 841

Variable in $scope returns NaN when used in a directive?

Im trying to make it so I can add a text area with a button in my angularJS app. There can be as many text areas as the user likes as its for adding content to a wizard system. Obviously, each textarea needs a different ID (as I plan to send it to an API) so I have made a stageIndex variable in my scope on the main controller. Then in my new stage directive, I make it so it appends the parent div with another textarea with the stageIndex as the id.... But it just comes out with NaN rather than the number I specified. Any ideas? app.controller("admin", function($scope, $location, $http, $state){

app.controller("admin", function($scope, $location, $http, $state){
    $scope.stageIndex = 0;
    // My other code here
});

app.directive('newstage', function(){ // This is my buttons directive, hence the element.click()
    return function(scope, element, attrs){
        element.click(function($scope){
            $scope.stageIndex += 1;
            element.parent().append("<textarea ng-attr-id="+ 'stage-' + $scope.stageIndex +"></textarea>");
        });
    }
});

Upvotes: 0

Views: 1280

Answers (1)

apairet
apairet

Reputation: 3162

The callback you provide to click is not called with $scope and there is not dependency injection performed there. Replace $scope.stageIndex += 1; by scope.stageIndex += 1;.

The click function comes from jQuery: http://api.jquery.com/click/

app.controller("admin", function($scope, $location, $http, $state){
    $scope.stageIndex = 0;
    // My other code here
});

app.directive('newstage', function(){ // This is my buttons directive, hence the element.click()
    return function(scope, element, attrs){
        //element.click(function($scope){ // $scope is undefined here!!!
        // I would prefer do the following as it does not require jQuery and will work with jqLite
        element.on('click', function () {
            // use scope:
            scope.stageIndex += 1;
            element.parent().append("<textarea ng-attr-id="+ 'stage-' + $scope.stageIndex +"></textarea>");
        });
    }
});

Upvotes: 1

Related Questions