我正在尝试更新 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/