简体   繁体   English

ng-init最初没有获取范围值

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

I am calling a function on ng-init . 我在ng-init上调用一个函数。 this function takes the values from the scope. 此函数从范围中获取值。 Actually what happening is we load a page and on page load we use 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

But I am not getting a in console means getting undefined . 但是,我没有得到a控制台意味着获得undefined But after clicking on any button on page or some stuff. 但是单击页面上的任何按钮或一些东西之后。 I got a . 我有a Means I am not getting this on page load. 意味着我在页面加载时没有得到这个。

You have to call it as 您必须将其称为

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

Besides that there are chances that you might get undefined if ng-init is called before $scope.abc() 除此之外,如果在$scope.abc()之前调用ng-init ,您可能会变得不确定。

Make sure the scripts are loaded before the javascript functions. 确保在javascript函数之前加载脚本。 Otherwise you would get the values to be undefined. 否则,您将获得未定义的值。

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

Instead of using ng-init, you can directly call function in controller. 除了使用ng-init外,您还可以直接在控制器中调用function。 Something Like this : 像这样的东西:

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

It will simplify the process as it will execute only when everything is loaded and defined. 因为它将仅在加载并定义了所有内容后才执行,因此将简化该过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM