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

时间:2013-11-14 15:27:34

标签: angularjs

我正在尝试使用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未定义。不应该'有价值'吗?

6 个答案:

答案 0 :(得分:46)

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

演示:

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

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

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

答案 1 :(得分:40)

只需将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

答案 2 :(得分:4)

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);
    }
}

Fiddle

答案 3 :(得分:1)

就像CodeHater所说,你在变量设置之前访问它。

要解决此问题,请将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>

这应该有用!

答案 4 :(得分:1)

试用此代码

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>

答案 5 :(得分:-1)

我在使用$scope.$watch时遇到了一些问题,但在经过大量测试后,我发现我的data-ng-model="User.UserName"命名错误,在我将其更改为data-ng-model="UserName"后,一切正常。我希望它是导致问题的名称中的.