在控制器Angularjs中观看对象 [英] watch an object in controller Angularjs

查看:65
本文介绍了在控制器Angularjs中观看对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.form = {
        name: 'my name',
        age: '25'
    }

    $scope.$watch('form', function(newVal, oldVal){
        console.log(newVal);
    },true);
    
    $scope.foo= function(){
    $scope.form.name = 'abc';
    $scope.form.age = $scope.form.age++;
    }
    $scope.foo();
    
    $scope.bar= function(){
    $scope.form.name = 'xyz';
    $scope.form.age = $scope.form.age++;
    }
    $scope.bar();
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">{{form}}<br>
<label>Name:</label> <input type="text" ng-model="form.name"/><br>
        <label>Age:</label> <input type="text" ng-model="form.age"/>  </div>

在控制器中,我四次更改了'form'对象的属性,但是$ watch没有触发.从UI(输入)(如果我进行更改)可以正常工作

In controller I changed 'form' object property four time,But $watch not firing. From UI(input) if I change it works

推荐答案

您的情况是,我认为在所有快速更新过程中,角度摘要循环都没有时间通过​​.

Your case is that I assume that the angular Digest cycle did not had time to pass during all your rapid updates.

这里有一些参考资料可以帮助您更多地了解Angular 1.X的摘要周期:

Here is some references to understand more the digest cycle of Angular 1.X:

防止这种行为;您可以使用$ timeout(具有$ apply)依赖项强制摘要通过: https://docs.angularjs.org/api/ng/service/ $ timeout

The prevent that kind of behaviour; your can force the digest to pass using $timeout ( that has a $apply) dependency : https://docs.angularjs.org/api/ng/service/$timeout

示例:

$timeout(function(){
    $scope.form.name = name;
    $scope.form.age = $scope.form.age++;
})

我创建了一个jsfiddle来欺骗您的案件:

I have created a jsfiddle to illustrade your case :

http://jsfiddle.net/IgorMinar/ADukg/

这篇关于在控制器Angularjs中观看对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆