2

現在のスコープに存在しないプロパティにバインドすると、Javascript エラーが発生しないことに気付きました。実際、Angular は代わりにスコープに新しいプロパティを設定すると思います。

以前は KnockoutJS を使用していましたが、データ バインド式がビューモデルの未定義のプロパティを参照すると、JS エラーがスローされました。

同じことを行うように AngularJS を構成する方法はありますか? JSエラーメッセージがトラブルシューティングに役立つため、この「厳密な」検証アプローチを好みます

HTML の例:

<div ng-app>
    <div ng-controller="ctrl">
        {{username1}}
    </div>
</div>

そしてJavascript:

function ctrl( $scope ) {
    $scope.username = 'user1';
}

HTML のタイプミスは、バインディングが一致しないことを意味します。それを教えてくれるJSエラーを取得するのは素晴らしいことです...

4

2 に答える 2

2

You could potentially create a filter that checks for the property being undefined:

app.filter("throwUndefined", function ($exceptionHandler) {
        return function (input) {
            if (input === undefined) {
                $exceptionHandler(new Error("Property was undefined"),
                                  "throwUndefined filter");
            }
            return input;
        };
    });

Seems a bit of overhead but with HTML like this:

<div ng-app="myApp" ng-controller="myController">
    {{variable | throwUndefined}}
    {{variable1 | throwUndefined}}
</div>

The undefined variables will call the exception handler. There is not a way to see the property that triggered this or to see if it was because the property isn't defined or was set to the value undefined, but you could plumb the call stack to find it. It seems you want more trust between your view and the controller, though - i.e. I'd say have your controller check but if you do that you can always ensure a value is set.

Fiddle: http://jsfiddle.net/jeremylikness/BHjRg/

于 2014-02-18T17:37:07.193 に答える
0

これは例外をスローしません$scope.username1 == undefined$scopeは単なる JavaScript オブジェクトであるため、存在しないキーを要求すると、常に が返されundefinedます。{{undefined}}空の文字列に補間します。したがって、例外はありません。HTML に{{bacon}}. それが役立つことを願っています!

于 2014-02-18T16:58:37.060 に答える