gpt4 book ai didi

javascript - $scope 是否自动注入(inject)到 Angular js 中的 Controller ?

转载 作者:行者123 更新时间:2023-11-29 19:35:04 25 4
gpt4 key购买 nike

最初我以为 $scope 会自动注入(inject) Angular JS 中的 Controller 。但现在我很困惑。我写了一小段代码。

index.html

 <html ng-app>
<body ng-controller="Controller">
<input type="text" ng-model="fname">
<span ng-bind="fname"></span>
<body>
</html>

脚本.js

angular.module('docsSimpleDirective', [])
.controller('Controller', ['$http', function($scope) {
$scope.fname = 'Foo Bar';

}])

如您所见,我没有在此处将 $scope 注入(inject) Controller 。当页面加载时,它不会在文本字段或跨度上显示“Foo Bar”。但是当我开始在文本字段上写一些值时,它反射(reflect)在跨度上。这意味着在范围内声明的“fname”。但是为什么它没有显示在页面加载中。当我注入(inject) $scope 时一切正常。

最佳答案

您有几件不同的事情正在发生。

首先,您需要以某种方式将应用绑定(bind)到DOM,在本例中,您将模块命名为docsSimpleDirective,因此您需要将 ng-app="docsSimpleDirective 添加到 Controller 的同一级别或之上

<!-- added ng-app="docsSimpleDirective" -->
<div ng-app="docsSimpleDirective" ng-controller="Controller">
<input type="text" ng-model="fname">
<span ng-bind="fname"></span>
</div>

其次,您使用数组注解来定义依赖关系,这很好。如果您不这样做并且试图丑化您的代码,您将遇到问题。您当前绑定(bind)它的方式不会将 $scope 传递给您正在传递名称为 $scope$http 的 Controller 。

angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {
// Not ['$http', function($scope)....
$scope.fname = 'Foo Bar';
}])

如果你想将 $scope$http 传递给 Controller ​​,它将像这样定义。

.controller('Controller', ['$scope','$http', function($scope,$http) { 

简而言之,您可以执行 .controller('Controller', ['$scope','$http', function(foo,bar) { ...foo 将等于 $scopebar 将等于 $http。这样做是为了在代码被丑化和丑化时不会改变$scope$http 的文字字符串,因此引用不会被破坏。

Here is a working Fiddle

关于javascript - $scope 是否自动注入(inject)到 Angular js 中的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25547890/

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