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

Tim*_*imH 41 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>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

var testController = function ($scope) {
     console.log($scope.testInput);
}
Run Code Online (Sandbox Code Playgroud)

在javascrippt中,$ scope.testInput未定义.不应该'有价值'?

Alw*_*ner 46

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

演示:

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

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

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

  • 在这种情况下,你可能会想要使用`$ scope.$ watch`. (8认同)

Rob*_*Rob 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;
  }
}]);
Run Code Online (Sandbox Code Playgroud)

这是一个例子.

Plunker