javascript - 将 ng-model 属性绑定(bind)到更改的对象值如何更新 ng-model

标签 javascript jquery angularjs

我正在尝试更新 testVar1 输入的 ng-model attr。值成功获取

$scope.testVar1 = menuElements[$scope.element.id].value;

但是当我改变

的值时
 menuElements[$scope.element.id].value;

我希望 testVar1 与其输入 View 一起更新 这可能吗?如果是这样我做错了什么?我在下面做了一个函数来尝试将代码设置为 val = 2 但它没有成功,似乎范围变量仅在构建页面时更新(至少是我编写的方式)

HTML:

<div class="well">
    <label for="{{element.id}}">{{element.info}}:</label>

    <input class="ui-slider" type="range" ng-model="testVar1" ng-change="changeValue(element.id)" name="{{element.id}}" min="{{element.min}}" max="{{element.max}}" id="{{element.id}}"/>
    <button ng-click="setTestValue()">Test</button>
</div>

指令和 Controller

cordovaAngular.directive('myCustomer', function () {

    return {
        restrict: 'A',
        scope: {
            element: '=',
            elementArray: '='
        },
        templateUrl: elementURL,
        controller: function ($scope) {
            var test = JSON.stringify($scope.elementArray);
            $scope.selectedOption = "Success"
            $scope.testVar1 = menuElements[$scope.element.id].value;
            console.log($scope.testVar1);
            console.log($scope.element.id);
            $scope.changeOption = function (selectedItem) {
                $scope.selectedOption = selectedItem;
                // alert(1);
            }
            $scope.changeValue = function (id) {
                menuElements[id].onChange();
            }
            $scope.setTestValue = function () {

                menuElements[$scope.element.id].value = 2;
                $scope.testVar1.
                console.log($scope.testVar1);

            }
        }
    };
});

最佳答案

我认为你可以使用$watch

menuElements 分配给 $scope 变量并为其添加一个 $watch 监听器。

$scope.$watch('menuElements', function(newVal, oldVal){
    // When menuElementes change, update testVar1 here
    $scope.testVar1 = menuElements[$scope.element.id].value;
}, true);

AngularJS docs for $watch

关于javascript - 将 ng-model 属性绑定(bind)到更改的对象值如何更新 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23355535/

相关文章:

javascript - 使用 jquery 更改 anchor 文本和图标

javascript - 在 ng-repeat 中丢失 Controller 范围

javascript - 使用 javascript 调用 Angular js

javascript - 为什么我的 Ember 组件中的 .then() 内部没有 'this' 上下文

javascript - 使用 Uppy 槽神社上传图像返回 405 方法不允许

javascript - 访问图像元素的父对象属性

javascript - 我如何从 jquery 插件中引用主题 $(this)?

JavaScript : How to keep defined object descriptor of original objects after mixing them up?

javascript - 如何在node-red中创建类似mqtt-broker helper的东西

javascript - AngularJS。按数组过滤数组