2015-02-10 148 views
1

的角度控制器我有以下的填写范围变量:从隐藏的输入值

application.controller('ImageController', function ImageController($scope, ImageService) { 

    $scope.model = { 
    images: [], 
    multiple: false 
    } 

    $scope.$watch('model.multiple', function (newVal, oldVal) { 
    console.log(newVal); 
    console.log(oldVal); 
    }); 

} 

我需要从一个隐藏的输入获得$ scope.model.multiple值。

隐藏的输入值从服务器端填充。所以测试我有:

<input type="hidden" data-ng-model="model.multiple" data-ng-value="true" /> 

当我运行我的代码newVal和oldVal都是false ...为什么?

+0

什么呢这样设置

application.controller('ImageController', function ImageController($scope, $window, ImageService) { $scope.model = { images: [], multiple: $window.model.multiple } 

值'数据-ng-model =“model.multiple”'输出? – 2015-02-10 13:26:52

+0

newVal和oldValue都未定义 – 2015-02-10 13:45:12

回答

0

我不认为ngValue做你认为它的作用。它是用于选项(在选择)和单选按钮。 See docs here

简短的回答:在$范围$表中的值是假的,因为你在控制器$ scope.model.multiple设置为false,在视图中隐藏的输入没有得到绑定到模型你希望它会。

在你的代码中,我认为你正在试图在你的视图中设置model.multiple的值,无论如何也不可能。

这是我的意见,你应该在控制器中设置值为true。我看不出有什么理由需要在隐藏输入中处理它。你提到它来自“服务器”,但视图是由AngularJS渲染的 - 而不是其他服务器。

对输入进行双向绑定的目的是让用户编辑将会反映在您的模型中。由于它们不是用户可编辑的,因此对隐藏的输入没有任何绑定。隐藏的输入意味着表单提交,而Angular不会那样做。表格在Angular中有不同的用途。

看看这个plunk看看hidden inputs don't impact the model。查看:

<body ng-controller="MainCtrl"> 
    <input type="hidden" ng-model="model.multiple" ng-value="true" value="true" /> 
    <input type="hidden" ng-model="model.test" />Hidden inputs have no impact on the model. 
    <br>That's why this is blank: '{{model.test}}' 
</body> 

控制器:

app.controller('MainCtrl', function($scope) { 
    $scope.model = { 
    images: [], 
    multiple: false 
    } 

    $scope.$watch('model.multiple', function(newVal, oldVal) { 
    console.log('New: ' + newVal); 
    console.log('Old: ' + oldVal); 
    }); 
}); 
+0

我试过了,newVal和oldVal都未定义 – 2015-02-10 13:44:38

+0

我将它们视为false仍未定义。仍然在努力,虽然...... – 2015-02-10 13:47:54

+0

@MiguelMoura我已经完全更新了答案。看起来你不能通过隐藏的输入来影响模型,我想这不是你想要的或者应该做的。 – 2015-02-10 14:03:50

0

相反ngValue指令,你可以使用ngInit directive.Here是你如何能做到这一点。

ng-init="model.multiple=true"

+0

Angular文档不推荐使用ngInit:https://docs.angularjs.org/api/ng/directive/ngInit – 2015-02-10 15:51:26

1

如果你填入一输入隐藏服务器端的价值,并希望它成为角可用,做到这一点无论是在角的方式,用装载值,或者,如果一个JSON您没有访问到后端,或者如果你不想改变你的代码很多,呈现模板与ID,如:

<input type='hidden' id='hiddenValue' value='xx(server-side)xx'> 

,然后控制器把喜欢的东西里面:

$scope.value = document.getElementById('hiddenValue'); 
+0

刚刚遇到了这种情况。这个解决方案非常简单,我忽略了它。 – TrippRitter 2015-03-16 14:59:58