在 angularjs 中适应非标准属性

Adapting non-standard properties in angularjs

本文关键字:非标准 属性 angularjs      更新时间:2023-09-26

我有一个使用GWT 2.7从java编译到javascript的现有模型。此模型中的每个属性都有一个 getValue() 和一个 setValue() 方法。方法名称不会损坏。

我想在 {{}} 表达式中使用这些属性,特别是使用 ngModel 进行绑定。我正在使用"getterSetter"选项和$scope中的一个函数,该函数将getValue()/setValue()包装在angularJS getterSetter函数中。

问题是我不想在每个作用域中复制这个函数。有没有办法在 angularJS 表达式中访问全局函数?

从文档中:

角度表达式无法访问全局变量,如窗口、文档或位置。此限制是有意为之。它可以防止意外访问全局状态 - 这是细微错误的常见来源。

您可以将该功能附加到模型原型吗?这样,只要您有模型的实例,您就可以访问它。

或者,您可以创建一个包装类(基本上是一个视图模型),该类具有所需的接口,并委托给实际模型实例。

经过相当多的搜索和实验,我发现我可以使用directivecontroller将函数添加到scope中。

.directive('wrapped', function() {
    return {
        controller: function($scope) {
            $scope.wrapper = function(prop) {
                // turns signal into getterSetter
                return function(newVal) {
                    if (angular.isDefined(newVal)) {
                        prop.setValue(newVal);
                        }
                    return prop.getValue();
                    }
                }
            },
        scope : {
            model : '&'
            },
        templateUrl : 'template.html',
    }
})

然后,可以在模板中的表达式中使用作用域中的函数。

<p class="field {{model().status().isValid() ? 'valid' : 'invalid'}}">
    <span class="label">{{label}}:</span>
    <input type="text" ng-model="wrap(model())" ng-model-options="{getterSetter: true}" ></input>
</p>

我很想听听更有经验的 AngularJS 程序员是否有更惯用的方法来编写它。