簡體   English   中英

如何使用ng-init設置范圍屬性?

[英]How to set scope property with 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);
}

理想情況下,您應該使用@Beterraba建議的$watch來擺脫計時器:

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

小提琴

就像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>

這應該工作!

試試這個代碼

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> 

我在使用$scope.$watch遇到了一些問題$scope.$watch但經過大量測試后我發現我的data-ng-model="User.UserName"命名錯誤,之后我將其更改為data-ng-model="UserName"一切正常。 我希望它是. 在導致問題的名稱中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM