angular指令中的观察者没有触发



我创建了自己的指令,并观察如下属性:

angular.module('app', [])
.controller('pieController', ['$scope', function ($scope) {
    function initData() {
        var arr = [];
        for (var i = 0; i < 6; i++) {
            arr.push(parseInt(Math.random() * 100));
        }
        return arr;
    }
    var data = initData();
    $scope.data = data;
    $scope.changData = function () {
        var data = initData();
        $scope.data = data;
    }
}]).directive('eChart', [function () {
    function link($scope, element, attrs) {
        var myChart = echarts.init(element[0]);
        if (attrs.myOptions) {
            $scope.$watch(attrs.myOptions, function () {
                var options = $scope.$eval(attrs.myOptions);
                if (angular.isObject(options)) {
                    myChart.setOption(options);
                }
            }, true);
        }
    }
    return {
        restrict: 'A',
        link: link
    };
}]);

和HTML是这样的:

<div class="col-xs-12" ng-controller="pieController">
        <button ng-click="changData()">click me</button>
        <div e-chart my-options="{tooltip: {show: true},
        legend: {
            data: ['销量']
        },
        xAxis: [
            {
                type: 'category',
                data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
        }
        ],
        yAxis: [
        {
        type: 'value'
        }
        ],
        series: [
        {
        'name': '销量',
        'type': 'bar',
        'data': {{data}}
        }
        ]}" style="height: 400px;width: 100%;"></div>
    </div>
</div>

在我的控制器中,我改变了属性的值,但是观察者没有触发。

我做错了什么?

代码在

请使用attrs.$observe你的指令应该是这样的

 .directive('eChart', [function () {
    function link($scope, element, attrs) {
        element.text("innerText");
        //监听options变化
        if (attrs.myOptions) {
            attrs.$observe('myOptions', function () {
                console.log("变了")
                var options = $scope.$eval(attrs.myOptions);
                element.text(attrs.myOptions);
            })
        }
    }
    return {
        restrict: 'A',
        link: link
    };
}]);

我认为你应该直接绑定数据。

app.directive('eChart', [function() {
    function link($scope, element, attrs) {
        if (attrs.myOptions) {
            $scope.$watch('data', function(newValue, oldValue) {
                if (angular.isObject(newValue)) {
                    console.log('change');
                }
            }, true);
        }
    }
    return {
        restrict: 'A',
        scope: {
            data: '=myData'
        },
        link: link
    };
}]);
<div e-chart my-data="data" my-options="... your options ..."></div>

最新更新