gpt4 book ai didi

javascript - 从 Controller 读取 ng-init 数据

转载 作者:行者123 更新时间:2023-12-01 02:27:14 24 4
gpt4 key购买 nike

我是 angularJS 的新手,我想从 Controller 访问 ng-init 数据,但总是返回未定义,这里是我的代码

HTML

<div class="row" ng-controller="IFuseController" ng-init="myText='Hello World!'">
....
</div>

Angular Controller

uniqcApp.controller('IFuseController', function (IFuseService, $scope) {
console.log("Cingda " + $scope.myText); //return undefined
});

有什么想法吗?

最佳答案

发生这种情况是因为您的 Controller 在加载时被调用,而此时您没有为变量 myText 设置值。

文本加载后,您需要触发一个事件。

演示

var uniqcApp = angular.module('uniqueApp',[]);
uniqcApp.controller('IFuseController', function ($scope){
$scope.read = function(){
console.log("Cingda " + $scope.myText);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="uniqueApp">
<div class="row" ng-controller="IFuseController" ng-init="myText='Hello World!'">
<button ng-click="read()">Read initial value</button>
</div>
</body>

关于javascript - 从 Controller 读取 ng-init 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48655769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com