[英]Angularjs custom directive two way binding not working
我創建自定義指令並使用兩種方式綁定(=)
但是我想觀察模型在指令中更改時控制器中的更改。
<div ng-app="zippyModule">
<div ng-controller="Ctrl3">
Title: <input ng-model="title">
<hr>
<div class="zippy" zippy-title="title" ff="titleChanged()"></div>
</div>
</div>
function Ctrl3($scope) {
$scope.title = 'Lorem Ipsum';
$scope.titleChanged = function() {
//ALERT COMMING WITH OLD VALUE NOT UPDATED
alert($scope.title);
}
}
angular.module('zippyModule', [])
.directive('zippy', function(){
return {
restrict: 'C',
replace: true,
scope: { title:'=zippyTitle',f:'&ff' },
template: '<input type="text" value="{{title}}"style="width: 90%" ng-click="onclick()"/>',
link: function(scope, element, attrs) {
// Your controller
scope.onclick = function() {
scope.title +="_";
if (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest') {
scope.$apply();
}
scope.f();
}
}
}
});
titleChanged方法正在調用,但是$ scope.title帶有舊值。 如果我刪除
if (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest') {
如果if並調用direcly scope。$ apply()方法,
正在應用進行中異常拋出。
正如@Omri所說,您應該將模型值放在作用域內的對象內,而不是直接在作用域上具有字符串。
但是,您可能只想使用ng-model來處理跟蹤模型更改:
angular.module('zippyModule', [])
.controller('Ctrl3', function($scope) {
$scope.model = {title : 'Lorem Ipsum'};
$scope.titleChanged = function() {
//ALERT COMMING WITH OLD VALUE NOT UPDATED
alert($scope.model.title);
}
})
.directive('zippy', function(){
return {
restrict: 'C',
replace: true,
scope: {f:'&ff' },
require: 'ngModel',
template: '<input type="text" style="width: 90%" ng-click="onclick()"/>',
link: function(scope, element, attrs, ctrl) {
// Use ngModelController
ctrl.$render = function() {
element.val(ctrl.$modelValue);
};
scope.onclick = function() {
var newVal = ctrl.$modelValue + '_';
element.val(newVal);
ctrl.$setViewValue(newVal);
scope.f();
}
}
}
});
然后更新您的HTML以使用ng-model:
<div ng-app="zippyModule">
<div ng-controller="Ctrl3">
Title: <input ng-model="model.title">
<hr>
<div class="zippy" zippy-title ng-model="model.title" ff="titleChanged()">
</div>
</div>
</div>
小提琴: https : //jsfiddle.net/sLx9do3c/
查看ngModelController的文檔,了解您最終可能需要的所有其他功能。 https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.