我有一个输入和选择标签的指令组合,所有源代码都在plunker中可用
我是 angularJS 的新手,这是我在阅读了一些教程后的第一个指令。当我更改选择选项时,绑定范围 item1 没有正确更改!!!!我希望 item1 必须使用 selectedchanged 函数中的选定项目进行更新
感谢任何帮助或改进
codecombo 指令模板:
<span>
<input ng-model="code" ng-change="codechanged()">
<select ng-model="selecteditem" ng-change="selectchanged()" ng-options="item as item[propertytitle] for item in list" class="codecombo-select"></select>
</span>
代码组合脚本:
app.directive('codecombo', function($compile) {
return {
restrict:'A',
scope:{
propertyid:'@',
propertycode:'@',
propertytitle:'@',
list:'=' ,
selecteditem:'=',
selectedchanged:'&'
},
templateUrl:'template.html',
link:
{
pre: function (scope, element, attrs, controller) {
/*make some property optional*/
if(!attrs.propertytitle) attrs.propertytitle="title";
if(!attrs.propertyid) attrs.propertyid="id";
if(!attrs.propertycode) attrs.propertycode="code";
},
post: function (scope, element, attrs, controller) {
var select=element.find('select');
var input=element.find('input');
/*some code delete for save space ...*/
scope.code;
/*select option changed*/
scope.selectchanged=function(){
console.log('select-changed');
console.log(scope.selecteditem);
if(scope.selecteditem!==null){
fillSelectedProperties(scope.selecteditem);
}
else
emptySelectedProperties();
scope.selectedchanged();
}
/*input text changed*/
scope.codechanged=function(){
console.log('code-changed');
scope.selecteditem=findByCode(scope.list,scope.code);
console.log(scope.selecteditem);
scope.selectchanged();
}
}
}
}
});
index.html 中的 codecombo 用法:
<div codecombo list="testlist" selecteditem="item1" selectedchanged="selectedchanged()"></div>
这是控制器:
app.controller('MainCtrl', function($scope) {
$scope.testlist=[
{id:1,code:100,title:'Item no.100'},
{id:2,code:200,title:'Item no.200'},
{id:3,code:300,title:'Item no.300'},
{id:4,code:400,title:'Item no.400'}
];
$scope.selectedchanged=function(){
/*
i want do some staff with item1 here and expect to be updated for each selectedchanged
but seem it has previous value
*/
console.log($scope.item1);
$scope.title=$scope.item1.title;
}
});