我有一个上传文件的指令,该文件与服务器通信并返回scope.dbInsertId
。我想看这个,然后用这个值更新ng-model。我无法使用$apply
让它工作。这是我的代码:
scope.$watch('dbInsertId', function(newValue, oldValue) {
if (newValue)
scope.$apply(function() {
scope.ngModel = scope.dbInsertId;
});
console.log("I see a data change!");
return ngModel.$modelValue;
}, true);
我的代码错了吗?
答案 0 :(得分:2)
我对你问题的回答
<div ng-app="app">
<div ng-controller="MyController">
<form name="someForm">
<div this-directive ng-model="theModel"></div>
<div>theModel='{{ theModel }}'</div>
</form>
</div>
</div>
var app = angular.module('app', []);
app.controller('MyController', function($scope,$rootScope,$log) {
$scope.theModel = '';
$scope.$watch('theModel',function(newVal,oldVal){
$log.info('in *MyController* model value changed',newVal,oldVal);
});
});
app.directive('thisDirective', function($compile, $timeout, $log) {
return {
scope: {
ngModel: '='
},
require: 'ngModel',
template: '<input type="text" ng-model="ngModel" /><div child-directive ng-model="ngModel"></div>',
link: function(scope, element, attrs, ngModel) {
}, // end link
} // end return
});
app.directive('childDirective', function($compile, $timeout, $log) {
return {
scope: {
ngModel: '='
},
template: '<input type="text" ng-model="ngModel" />',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
},
} // end return
});
答案 1 :(得分:1)
您需要scope
:
scope.$watch('dbInsertId', function(newValue, oldValue, scope) { // here
if (newValue)
scope.$apply(function() {
scope.ngModel = scope.dbInsertId;
});
console.log("I see a data change!");
return ngModel.$modelValue;
}, true);