簡體   English   中英

ng-init最初沒有獲取范圍值

[英]ng-init is not getting the scope values initially

我在ng-init上調用一個函數。 此函數從范圍中獲取值。 實際上發生的事情是我們加載頁面,並在頁面加載時使用ng-init

<div ng-init="somefunction(c,d)">
</div>

$scope.somefunction = function() {
  console.log($scope.a);
}

$scope.abc = function() {
  //calling another function 
  $scope.xyz();
}
$scope.xyz = function() {
  $scope.a = "hello";
}
$scope.abc();//called on controller load

但是,我沒有得到a控制台意味着獲得undefined 但是單擊頁面上的任何按鈕或一些東西之后。 我有a 意味着我在頁面加載時沒有得到這個。

您必須將其稱為

<div ng-init="somefunction()">
</div>

除此之外,如果在$scope.abc()之前調用ng-init ,您可能會變得不確定。

確保在javascript函數之前加載腳本。 否則,您將獲得未定義的值。

 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <div ng-init="somefunction()"> </div> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.somefunction = function() { $scope.abc(); console.log($scope.a); } $scope.abc = function() { //calling another function $scope.xyz(); } $scope.xyz = function() { $scope.a = "hello"; } }); </script> 

除了使用ng-init外,您還可以直接在控制器中調用function。 像這樣的東西:

<div></div>
$scope.a = '';
$scope.somefunction = function() {
  console.log($scope.a);
}

$scope.abc = function() {
  //calling another function 
  $scope.xyz();
}
$scope.xyz = function() {
  $scope.a = "hello";
}
$scope.abc();//called on controller load
$scope.somefunction();

因為它將僅在加載並定義了所有內容后才執行,因此將簡化該過程。

暫無
暫無

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

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