为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的 javascript obj 没有在 angularjs 中更新?

为什么我的 javascript obj 没有在 angularjs 中更新?

饮歌长啸 2021-12-02 15:51:19
我正在使用 angularJS,并具有以下控制器变量:cont.flag = 0;cont.obj = {objFlag: cont.flag, objFunction: cont.func};cont.func = function() {    // do stuff}该cont.flag变量绑定到 HTML 中的用户输入。因此,当该值发生变化时,我希望objFlag更新它当前未执行的操作。此外,该objFunction值似乎始终未定义。这是因为 cont.obj 是在 cont.func 之上声明的吗?编辑:如果不清楚,则 cont.flag 变量正在由用户输入正确更新,它只是我 obj 中没有更新的 cont.flag 指针。此外,objFunction 没有填充我传递给它的函数。这是我在评论中提供的更多信息,说明为什么我将这些变量放在对象中而不是直接操作它们:所以我有一系列我想链接在一起的函数,但我想控制哪些函数可以运行. 所以我为每个函数都有一个 obj: objFlag 表示是否应该将函数添加到链中, objFunction 是要运行的实际函数。我想要一种将 objFlag 与它附带的 objFunction 相关联的方法
查看完整描述

2 回答

?
DIEA

TA贡献1820条经验 获得超2个赞

不随 AngularobjFlag变化的原因cont.flag与 Angular 无关。这是本机 Javascript 行为。

这个说法:

cont.obj = {objFlag: cont.flag, objFunction: cont.func};

只有一个初始分配cont.flagobjFlag之间不存在正在进行的链路objFlagcont.flag


查看完整回答
反对 回复 2021-12-02
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

让我们以其他方式思考您的代码


cont.flag = 0;

cont.obj = {objFlag: cont.flag, objFunction: cont.func};


cont.func = function() {}

这相当于


var cont = {

  flag: 0,

  obj: {objFlag: cont.flag, objFunction: cont.func},

  func: function() {}

}


console.log(cont.obj);


您可以在cont此处看到未定义的结果(无法读取未定义的属性“标志”)。我们无法将变量访问到同一对象内的另一个变量中。


所以,你会想到在this这里使用


var cont = {

  flag: 0,

  obj: {objFlag: this.flag, objFunction: this.func},

  func: function() {}

}


console.log(cont.obj);


同样,您将获得未定义的值,因为我们无法使用另一个变量访问对象元素。但是我们可以使用函数来访问它们。所以最后一个选择是使用 obj 的 getter 函数将带有其他变量数据的 json 返回到一个变量中。(在自引用 json 对象中)


var cont = {

  flag: 0,

  get obj() {return {objFlag: cont.flag, objFunction: cont.func}},

  /*or*/

  /* get obj() {return {objFlag: this.flag, objFunction: this.func}},*/

  func: function() {}

}

console.log("Before change", cont.obj);


//change

cont.flag = 10;


console.log("After change", cont.obj);


更新


现在,将您的案例与上面的解释结合起来,cont控制器的参考在哪里,如何在角度控制器中添加 getter 属性。


Object.defineProperty方法就是你所需要的。所以你的最终代码将是:


cont.flag = 0;

Object.defineProperty(cont, 'obj', {

    get: function() {

        return {objFlag: cont.flag, objFunction: cont.func}

    }

 });


cont.func = function() {}


// you can access obj property to see the values

console.log(cont.obj)


查看完整回答
反对 回复 2021-12-02
  • 2 回答
  • 0 关注
  • 195 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信