我创建自定义指令并使用双向绑定(=)
但我想要观察当模型在指令中改变时控制器中的变化。
<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') {它直接调用scope.$apply()方法,
正在进行中的应用异常正在引发。
发布于 2016-06-01 20:10:27
正如@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
https://stackoverflow.com/questions/27401261
复制相似问题