AngularJS $ scope更新,包含两个新对象($ scope),其成员函数更新$ scope

时间:2015-08-29 14:59:11

标签: angularjs angularjs-scope javascript-objects

Angular和JS一般都是新手。在阅读了很多有关角度的范围后,我仍然对这个错误感到茫然 - 请帮忙!我有一个控制器,它依赖于两个独立的js函数,这两个函数都将控制器的$ scope作为参数。关于如何在这里更新$ scope,我显然缺少一些东西 - 变量更新一次(延迟一次调用,第一次为null - 如果我在新构造的对象中明确设置它,它永远不会更新)并且再也不会

    //in the controller...

//have tried with and without this $watch, no dice. window pops with the correct value, 
//then the immediately pops again with the very first value entered since a new window  
var x;
$scope.$watch('bar.id', function(newval, oldval) {
      window.alert($scope.bar.id);
      x=newval;
    });

user = new userScript($scope, $http, $timeout, $user, socket,
        userId,
        'myForm', 'foo',
        '/api/user/show/' + userId, '/api/user/upsert/'+ userId,
        'userUnits');

unit = new unitScript($scope, $http, $timeout, $user, socket,
        userId,
        'myForm', 'bar', '/api/unit/upsert/' + null,
        'unitFields');

//unit.save() calls unit/upsert (uses $http.put) with a null argument, which creates a new record.
//it also sets $scope['bar'].id to the key of that new record.
//the intent is for the $watch to update that part of the scope, then
//save it (have tried this with/without $watch), then push that value onto 
//$scope.foo.units[], which is then upserted as userUnits[] in a call to user.save()  
$scope.newUnit = function(){
        unit.save();
        $scope.foo.units.push(x);
        user.save();
      }

//从ng-click按钮元素调用newUnit。

查看数据库,用户存储的数组看起来像 userUnits [null,firstId,firstId,firstId ....]

好像这里有两个相互冲突的$ scope版本,一个覆盖另一个(注释掉user.save()会停止覆盖,但会阻止上传我想保存的数据)。但是,我无法准确地将它们的交互方式拼凑在一起。我试过使用$ apply也无济于事。提前感谢您的任何时间/建议!

0 个答案:

没有答案