考虑以下指令:
<div address
street-address-model="client.streetAddress"
suburb-model="client.suburb"></div>
angular.module("Demo", [])
.controller("DemoCtrl", function($scope) {
$scope.client = {
streetAddress: '10 Morang Drive',
suburb: 'Mill Park'
};
})
.directive("address", function() {
return {
scope: {
streetAddressModel: '=',
suburbModel: '='
},
template: " \
<div> \
Street Name: <input type='text' ng-model='streetAddressModel'> \
Suburb: <input type='text' ng-model='suburbModel'> \
</div> \
"
};
});
我想在此指令中添加另一个参数:on-street-address-change="<expression>"
。
请注意,表达式可以是任何有效的角度表达式,例如:
on-street-address-change="doSomething(x)"
on-street-address-change="doSomething(x, y, z)"
on-street-address-change="myVar = 'value'"
一旦街道名称输入值发生变化(例如我输入上有ng-change="<expression>"
),就应该评估此表达式。
我如何添加此类功能?
答案 0 :(得分:4)
尝试这种方式:
HTML:
<div address
street-address-model="client.streetAddress"
suburb-model="client.suburb"
on-street-address-change="doSomething(1)"
></div>
JS:
angular.module("Demo", [])
.controller("DemoCtrl", function($scope) {
$scope.client = {
streetAddress: '10 Morang Drive',
suburb: 'Mill Park'
};
$scope.doSomething = function(x){
console.log(x);
};
})
.directive("address", function($parse) {
return {
scope: {
streetAddressModel: '=',
suburbModel: '='
},
template: " \
<div> \
Street Name: <input type='text' ng-model='streetAddressModel'> \
Suburb: <input type='text' ng-model='suburbModel'> \
</div> \
",
link: function (scope, element, attrs) {
scope.$watch('streetAddressModel', function(newVal){
$parse(attrs.onStreetAddressChange)(scope.$parent);
});
}
};
});
编辑:找到了更好的方法:
scope: {
onStreetAddressChange: '&'
}
然后像这样执行:
scope.onStreetAddressChange();