Angular 带下划线或驼峰式大小写的 $watch 变量名未更新

Angular $watch variable name with underscore or camel case doesn't get updated

当我 $watch 名称中包含下划线或驼峰式大小写的变量时,$watch 不会触发。如果被 $watch'ed 的变量名不包含任何下划线或驼峰式大小写,它就可以工作。在 Angular 文档中,我没有发现任何关于变量名被 $watch'ed 的内容。

$watch 未能触发的代码如下: http://jsbin.com/potiferixu/1/edit?html,console,output

这是正确触发 $watch 的代码: http://jsbin.com/sulugukaka/2/edit?html,console,output

唯一的区别是变量名。

在AngularJS中,当您在指令中引用带有下划线的变量时,您必须使用驼峰式版本。

取自官方documentation:

Angular normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).

因此,您应该在以下范围内使用它:

scope: {
  fieldWithUnderscore: '='
},

$watch 里面的这个:

console.log(scope.fieldWithUnderscore);

并且(正如您所指出的)也改变这个:

scope.$watch('fieldWithUnderscore'

更新版本http://jsbin.com/zoqupizuvi/2/edit