简体   繁体   中英

Directive doesn't fire on SELECT change event

I have this HTML code:

<select class="state ng-scope ng-pristine ng-invalid ng-invalid-required">
    <option value="" selected="selected" class="">Seleccione un estado</option>
</select>

And I wrote this directive:

app.directive('state', ['$http', function($http){
    return {
        restrict: 'C',
        link: function(scope, element, attrs) {
            console.log("element" + element);
            console.log("attrs" + attrs);
        }
    }
}]);

Why directive isn't fired?

I would add a ng-model on your select and then add a watch in your directive. Pass your variable into the directive and output your desired result. Pseudo code:

<select ng-model="myList" class="ng-scope ng-pristine ng-invalid ng-invalid-required">
    <option value="" selected="selected" class="">Seleccione un estado</option>
</select>

<span state selectedItem="myList"></span>

and your directive might look like:

  directive('state', ['$http', function($http){
        return {
            restrict: 'A',
            scope: {
                myList: '=myList'
            },
            link: function(scope, element, attrs) {
                scope.$watch('myList', function (newValue, oldValue) {
                    console.log(changed);
                }
            }
        }
    }])

The problem is I wasn't listen on change event. The right code is:

link: function(scope, element, attrs) {
   console.log(element);
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM