Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs, $scope.variable is undefined in a directive

In my html file , I use a directive which is a searchBox:

<ng-lms-search-box searchType="Author" maxResult=5 data-ng-model="searchText"> </ng-lms-search-box>

And this is the function where I define the directive in app.js:

lmsModule.directive('ngLmsSearchBox', [ '$http', function($http) {
    return {
        restrict : 'E',
        replace : 'true',
        $scope : {
            searchType : '@searchType',
            searchText : '@ngModel',
        },
        templateUrl : '../templates/searchBox.html',
        bindToController : true,
        link : function($scope, element, attrs) {
            console.log($scope.searchType);
            if ($scope.searchType == "Author") {
                element.bind('keyup', function() {
                    $http.post("listAuthor/" + $scope.searchText + "/1", {
                        'Content-Type' : 'application/json'
                    }).success(function(data) {
                        $scope.$emit("passData", data);
                    });
                });
            } else if ($scope.searchtype == "Publishers") {
            } else {
            }
        },
    };
} ]);

The $scope.searchType which should be "author" is, however, "undefined".

Anyone knows why? Thanks in advance!

like image 963
6324 Avatar asked Jan 21 '26 15:01

6324


2 Answers

HTML should be snake-case:

  search-type="Author"

And camelCase in your directive definition.

 $scope.searchType
like image 157
pixelbits Avatar answered Jan 24 '26 09:01

pixelbits


declaring variable in the template should be with dash delimeter as below,because you have used scope variable as searchType , which is camel case. and its should be scope not $scope , inside DDO (directive defintion direcitve)

search-type

refer : https://docs.angularjs.org/guide/directive

<ng-lms-search-box search-type="Author" maxResult=5 data-ng-model="searchText"> </ng-lms-search-box>
like image 32
Shushanth Pallegar Avatar answered Jan 24 '26 08:01

Shushanth Pallegar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!