gpt4 book ai didi

javascript - 属性更改时不触发指令

转载 作者:行者123 更新时间:2023-12-03 10:19:24 24 4
gpt4 key购买 nike

我有两个下拉菜单,用户可以从中进行选择。并根据这些值,将属性发送到指令并调用相应的函数。

问题在于值更改时不会调用指令。

这是html代码:

<div ng-controller=visCtrl> 

<select ng-model="selectedDistrict" ng-options="item as item for item in districts " ng-init="selectedDistrict='GUNTUR'"></select>
<select ng-model="selectedYear" ng-init="selectedYear='2005'" ng-options="item as item.YEAR for item in opendata | filter:{ DISTRICT: selectedDistrict }"></select>


<div ng-repeat="item in categories">
<div id="containervis-item" ng-init="init(item.value)" class="container col-sm-12">
<div scatter-chart city-name={{selectedDistrict}} crime-name={{item}} current-year={{selectedYear}} vis-file=dataFile id="divVisScatter-{{item}}" class="divVis divVisScatter col-sm-6">
{{item}}
</div>
<div linear-chart city-name={{selectedDistrict}} crime-name={{item}} vis-file=dataFile class="divVis divVisLine col-sm-6"></div>
</div>
</div>
</div>

这是指令代码:

myApp.directive('scatterChart', function($window){
return{
restrict:'EA',
template:"<svg width='850' height='200'></svg>",
link: function(scope, elem, attrs){

var d3 = $window.d3;
var rawSvg=elem.find('svg');
var svg = d3.select(rawSvg[0]);

var cityName=attrs.cityName;
var crime=attrs.crimeName;
var year=attrs.currentYear;


console.log(cityName);//doesnt get called when selection is made
}
};
});

仅使用初始值调用指令。此外,在做出选择后,DOM 会发生更改,并且 city-namecrime-name 属性会获得新值,但不会调用该函数。

最佳答案

“应该调用相应的函数”是指链接函数吗?链接函数在编译阶段之后执行一次,它是将事件监听器附加到 HTML 模板等的正确位置。检查here更多细节。

如果您想在每次属性值更改时执行函数,则必须$watch它,并将所有必要的代码包含到$watch函数中。< br/>例如。

scope.$watch(function() {
return attrs.cityName;
}, function(value) {
console.log(value);
})

关于javascript - 属性更改时不触发指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29716696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com