指令不会触发SELECT更改事件

时间:2014-03-06 14:09:22

标签: javascript angularjs angularjs-directive

我有这个HTML代码:

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

我写了这个指令:

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

为什么不解雇指令?

2 个答案:

答案 0 :(得分:1)

我会在你的选择中添加一个ng-model,然后在你的指令中添加一个watch。将变量传递给指令并输出所需的结果。伪代码:

<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>

,你的指令可能如下:

  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);
                }
            }
        }
    }])

答案 1 :(得分:0)

问题是我没有听change事件。正确的代码是:

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