观看响应时有问题。
我有一个设置为设置,这是我的观点:
<input type="text" class="form-control" ng-model="settings.test.one" />
<input type="text" class="form-control" ng-model="settings.test.second" />
这是我的控制器:
app.controller('SettingsCtrl', function ($scope, settingsFactory, Test) {
var vm = this;
settingsFactory.test().then(function(response){
vm.test = response;
})
///// OR
vm.test = Test; // this is from ui-router resolve
$scope.$watch(angular.bind('vm', function () {
return vm.test;
}), function (newV, oldV) {
console.log(newV, oldV);
});
$scope.$watch(function watch(scope){
return vm.test;
}), function handle(newV, oldV) {
console.log(newV, oldV);
});
$scope.$watch('vm', function (newVal, oldVal) {
console.log('newVal, oldVal', newVal, oldVal);
});
});
我一直在搜索并找到了不同的解决方案,但其中没有其他解决方案。
****仅是第一次手表,当控制器加载并看到我的控制台日志时,但是当我尝试进行更改时,观察者什么也不做。
我做错了什么?
如果我没有错,则首次加载控制器时,您的$手表被击中,但是当您更改对象中的某些内容时。如果是真的,请尝试以下操作:
$scope.$watch('vm', function (newVal, oldVal) {
console.log('newVal, oldVal', newVal, oldVal);
}, true);
默认情况下,$ Watch函数观看引用,因此,如果您仅更改手表对象的属性,则不会触发。通过在末尾添加true
,您可以开始深入观看,每次更改对象的属性时,都会受到打击。
angularjs仍然按预期工作:
angular
.module('app', [])
.controller('SettingsCtrl', function($scope) {
var vm = this
vm.test = ''
$scope.$watch(function watch(scope) {
return vm.test;
},
function handle(newV, oldV) {
if (newV && newV.name && newV.name !== oldV.name) {
vm.test.watchedName = newV.name.toUpperCase()
}
}, true);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app'>
<div ng-controller='SettingsCtrl as settings'>
<input type='text' ng-model='settings.test.name' />
<pre><code>
{{ settings.test.watchedName }}
</code></pre>
</div>
</div>
尝试以下遵循手表的代码。
$scope.$watch(function(){
return ctrl.test;
},function(newVal,oldVal){
console.log(newVal,oldVal);
},true)
这是工作小提琴
您将需要对物体上的深度观看。
此链接$观看对象将帮助您理解这一点。
请尝试将VM变量称为controler.vmvariable。控制器是您的控制器名称,然后在VM中分配的变量。
$scope.$watch('controller.vmVariable', function (newVal, oldVal) {
console.log('newVal, oldVal', newVal, oldVal);
});
参考GitHub帖子后对我有用的是什么(https://github.com/johnpapa/angular-styleguide/issues/428)和(http://jsbin.com/levewagufo/edit?html,js,Console,Output)是将控制器从vm = this重命名为(在您的情况下)设置=在编写控制器的开头。从视图中,这确保参考文献符合"控制器为"声明。希望这有帮助
视图:
ng-controller="AddDetailController as addDetailsCtrl"
在控制器JS文件中:
$scope.$watch('addDetailsCtrl.currentPage', function (current, original) {
console.log(current + ":" + original); });