如何使用ng-init初始化的脚本代码访问$ scope变量

时间:2019-03-02 15:39:03

标签: angularjs

我像下面这样尝试,但是结果是“未定义”

请帮助我

这是代码:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" ng-init="carname='Volvo'">

<h1>{{carname}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   //I want to get value of $scope.carname here
     alert($scope.carname); 
});
</script>

2 个答案:

答案 0 :(得分:1)

这是默认行为,因为先创建控制器,然后设置 carname='Volvo'

作为解决方法,您应该改用下面的函数

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
     $scope.init = function(carName) {
        $scope.carname = carName;
        alert($scope.carname);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" ng-init="init('Volvo')">

<h1>{{carname}}</h1>

</div>

答案 1 :(得分:0)

您可能想ng-init一个函数并在那里获取值。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  
  $scope.setCarName = function() {
    //I want to get value of $scope.carname here
    $scope.carname = 'Volvo';
    alert($scope.carname);
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl" ng-init="setCarName()">

    <h1>{{carname}}</h1>

  </div>