【发布时间】:2015-07-12 22:58:43
【问题描述】:
我已经为自定义指令的属性添加了$watch()(它又是范围变量)。当作用域变量的值改变时,指令的相应属性值不会改变,因此值函数不会被触发。
这里是html代码:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="js/angular.min.js"></script>
<!-- some code -->
</head>
<body>
<div ng-controller=visCtrl class="container col-sm-12">
<div timeline-chart vis-file=skillFile class="divVis divVisLine col-sm-12">
<!-- some code -->
</div>
<div skill-chart vis-file=skillFile exp-key={{selectedDataKey}} class="divVis divVisLine col-sm-12">
<!-- some code -->
</div>
</div>
<!-- some code -->
</body>
</html>
这里是JS代码:
var myApp = angular.module('myApp', ['ui.utils']);
myApp.controller('visCtrl', function($scope) {
$scope.selectedDataKey = 4;
});
myApp.directive('timelineChart', function($window) {
return {
restrict: 'EA',
link: function(scope, elem, attrs) {
drawTimeLine = function() {
var chart = d3.timeline()
//some code
.click(function(d, i, datum) {
//console.log(scope);
console.log("previously selectedDataKey was:" + scope.selectedDataKey);
scope.selectedDataKey = datum.key;
console.log("selectedDataKey changed to:" + scope.selectedDataKey);
});
d3.csv(dataFile, function(error, data) {
//some code
}
drawTimeLine();
}
}
});
myApp.directive('skillChart', function($window) {
return {
restrict: 'EA',
/*template:"<svg width='850' height='200'></svg>",*/
link: function(scope, elem, attrs) {
var dataKey = attrs.expKey || false;
scope.$watch(function() {
return attrs.expKey;
}, function(value, oldval) {
dataKey = value || false;
console.log("skillChart dataKey changed to:" + dataKey);
if (dataKey) {
drawSkillChart();
}
});
drawSkillChart = function() {
//some code
}
drawSkillChart();
}
}
});
【问题讨论】:
-
您的问题中是否也缺少 watchexpression ?文档定义了 watch here 您希望收到通知的变量/模型。
标签: javascript angularjs