I created my own directive and watching an attribute like this:
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
};
}]);
and the html is like this:
<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>
In my controller,i change the value of the attribute,but the watcher doesn't trigger.
So what i am doing wrong?Thanks.
2 Answers 2
Please use attrs.$observe
You directive should be like this
.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
};
}]);
Sign up to request clarification or add additional context in comments.
1 Comment
Qi Tang
If you think this answer solves your problem plz accept it.
I thought you should bind the data directly.
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>
Comments
lang-js
changeDatafunction in controller trying to change and if you console.log()attrs.myOptionsthen do you see updated data ??changeDatafunction is trying to change thedatain $scope,and thisdatais also bind to the attributemy-options。attrs.myOptionscause the watcher does't work