您可以登录角数据绑定错误?您可以、绑定、错误、数据

2023-09-14 00:10:59 作者:隔壁老王来约会

反正是有记录,如果绑定属性或前pression失败?

is there anyway to log if a bound property or expression fails?

即。

<input type="text" ng-model="user.name" />

登录时的用户名或未定义?

Log when user or name is undefined?

编辑:似乎有很多混乱的关于如何这可能发生。让我们假设我用一个视图模型的多个视图(或者我很健忘)

There seems to be a lot of confusion about how this could happen. Lets assume I use a viewmodel for multiple views (Or I'm very forgetful)

Imaginge我改变JS code这样的名字现在user.firstName,我忘了更新我的看法。我想拥有它记录在运行时这样我就可以修复它​​。

Imaginge that I change the JS code so that name is now user.firstName and I forget to update my view. I would like to have it logged at runtime so I can fix it.

推荐答案

正如其他人在评论中提到,数据绑定时,在范围并不定义的属性不会不及格本身,而是将创建属性上透明的范围。

As others have mentioned in the comments, the data binding won't "fail" per se when the attribute is not defined in the scope, but will create that attribute on the scope transparently.

如果您想进行一些通知行为时找不到名称,您可以手动装饰NG-模式指令来检查,如果它的价值就在它插入到DOM的时间范围定义得到它。

If you want some notification behaviour when the name isn't found, you can get it manually by decorating the ng-model directive to check if its value is defined on the scope at the time it's inserted into the DOM.

.config(['$provide', function($provide) {
        $provide.decorator('ngModelDirective', ['$delegate', function($delegate){
            var directive = $delegate[0];

            // Save the old link function
            var link = directive.link;
            directive.compile = function() {
                return function(scope, element, attrs) {
                    link.apply(this, arguments);

                    // Now that we've applied the old link function, we can add
                    // any extra checks or steps we want
                    if (!objHasProperty(scope, attrs.ngModel)) {
                        alert("using ng-model value '" + attrs.ngModel +"' that wasn't defined first!"
                    }
                };
            };

            return $delegate;
        }]);
    }])

这将检查控制器的范围和警报的NG-模型值的定义,如果它没有设置。

This will check for a definition of the ng-model value in the controller's scope and alert if it's not set.

请参阅工作的jsfiddle 的如何可能会记录一个错字。

See a working jsfiddle of how this might log a typo.

我没有测试过这还是想过每一个场景中,因此有可能它真的破的地方...我还不能确定它会如何处理找到父的范围中定义的attrs。

I haven't tested this in or thought about every scenario, so it's possible it's really broken somewhere... I'm also unsure of how it'll deal with finding attrs that are defined in the parent's scope.

此外,请参阅这个漂亮的博客文章更多在装饰指令。

Also, see this nice blog post for more on decorating directives.