![](/img/trans.png)
[英]How to pass a custom directive attribute to custom directive child element in Angular 1.5?
[英]Refresh element of custom attribute directive in Angular
我有一個自定義的角度指令,用於更改項目價格的顯示。 它以年值存儲,我需要在允許用戶以年或月方式查看/編輯之間切換。 因此,我的自定義指令在我的輸入框上起作用(無法將其用於標簽,div,span,但這是另一個問題)。
我能夠看到,當我切換屬性時,它拾取了更改,但是輸入中的值沒有更改,並且我認為這是因為未重新渲染元素。 我有什么辦法可以強迫這種情況發生?
這是我的指令
angular.module('common.directive').directive('priceMonthly', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
var perMonth = false;
attr.$observe('priceMonthly', function(isMonthly) {
perMonth = (isMonthly.toLowerCase() === "true");
console.log("per month is " + perMonth); //updating perMonth correctly at this point
//guessing I need to do something here or in the function that changes the value of the attribute
});
function fromView(value){
return perMonth ? value * 12 : value;
}
function toView(value){
return perMonth ? value / 12 : value;
}
ngModel.$parsers.push(fromView);
ngModel.$formatters.push(toView);
}
};
});
這是我正在使用的地方。
<input type="text" price-monthly="{{monthlySqftView}}"
class="form-control no-animate" name="item.priceLow"
ng-model="item.priceLow" ui-money-mask="2"/>
這是我現在所在的地方。 因此,如果下拉列表按月顯示,並且我輸入12,則價格正確為144,這將是全年價格。 現在,如果將下拉列表更改為逐年,則需要輸入更新為144。https ://jsfiddle.net/6tnbonzy/
@rschlachter,我不確定這是否可以幫助您。 AngularJS使用scope.digest()清除臟數據。 您可能需要將這行代碼放入您的方法中
attr.$observe('priceMonthly', function(isMonthly) {
perMonth = (isMonthly.toLowerCase() === "true");
console.log("per month is " + perMonth); //updating perMonth correctly at this point
//guessing I need to do something here or in the function that changes the value of the attribute
//put it here, if you instantiated scope already.
scope.digest();
//scope.apply();
});
希望它能工作
進行必要的更改后,請嘗試scope.$apply()
看來您想執行類似jsfiddle的操作 ?
<form name="ExampleForm">
<select ng-model="period">
<option value="monthly">monthly</option>
<option value="yearly">yearly</option>
</select>
<pre>
period = {{period}}
</pre>
Edit as {{period}}: <input price-monthly="obj.price" period="period" ng-model="obj.price" >
<pre>
price = {{obj.price}}
</pre>
</form>
和JS控制器
.controller('ExampleController', function($scope) {
$scope.period = 'monthly';})
和JS指令
.directive('priceMonthly', function() {
return {
restrict: 'A',
scope:{
priceMonthly:"=",
period:"="
},
link: function(scope) {
scope.$watch('period',function(newval){
if(newval=='monthly')
scope.priceMonthly = scope.priceMonthly*12;
if(newval=='yearly')
scope.priceMonthly = scope.priceMonthly/12;
})
}
};});
我希望這能幫到您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.