如何使用ng-init设置范围属性?

我想使用ng-init设置$ scope属性的值,并且我无法访问控制器的javascript中的值。 我究竟做错了什么? 这是一个小提琴: http : //jsfiddle.net/uce3H/

标记:

<body ng-app> <div ng-controller="testController" > <input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput='value'" /> </div> {{ testInput }} </body> 

JavaScript的:

 var testController = function ($scope) { console.log($scope.testInput); } 

在javascrippt中,$ scope.testInput是未定义的。 不应该是“价值”?

您正在尝试在Angular完成分配之前读取设置值。

演示:

 var testController = function ($scope, $timeout) { console.log('test'); $timeout(function(){ console.log($scope.testInput); },1000); } 

理想情况下,您应该使用$watch来build议@Beterraba来摆脱计时器:

 var testController = function ($scope) { console.log('test'); $scope.$watch("testInput", function(){ console.log($scope.testInput); }); } 

只需将ng-init设置为一个函数即可。 你不应该使用手表。

 <body ng-controller="MainCtrl" ng-init="init()"> <div ng-init="init('Blah')">{{ testInput }}</div> </body> app.controller('MainCtrl', ['$scope', function ($scope) { $scope.testInput = null; $scope.init = function(value) { $scope.testInput= value; } }]); 

这是一个例子。

Plunker

HTML:

 <body ng-app="App"> <div ng-controller="testController" > <input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput=123" /> </div> {{ testInput }} </body> 

JS:

 angular.module('App', []); testController = function ($scope) { console.log('test'); $scope.$watch('testInput', testShow, true); function testShow() { console.log($scope.testInput); } } 

小提琴

试试这个代码

 var app = angular.module('myapp', []); app.controller('testController', function ($scope, $http) { $scope.init = function(){ alert($scope.testInput); };}); 
 <body ng-app="myapp"> <div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" > </div> </body> 

像CodeHater一样,你在访问variables之前,

为了解决这个问题,将ng-init指令移至第一个div。

 <body ng-app> <div ng-controller="testController" ng-init="testInput='value'"> <input type="hidden" id="testInput" ng-model="testInput" /> {{ testInput }} </div> </body> 

这应该工作!

我有一些$scope.$watch麻烦,但经过大量的testing后,我发现我的data-ng-model="User.UserName"被严重命名,在我将其改为data-ng-model="UserName"一切正常。 我希望它是. 在导致问题的名称。