gpt4 book ai didi

javascript - AngularJS无法访问变量差异文件

转载 作者:行者123 更新时间:2023-11-28 17:36:58 26 4
gpt4 key购买 nike

我是 AngularJs 的新手。我刚刚开始学习依赖关系概念。但是在 app.jsformapp.js 之间分离文件时遇到问题。我无法访问 users 变量,因为它的文件是分开的。我如何访问该变量?我希望你们能帮我解决这个问题。提前谢谢您。

index.html

<!DOCTYPE html>
<html ng-app="training">
<head>
<link rel="stylesheet" type="text/css" href="../bootstrap.min.css" />
<script type="text/javascript" src="../angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="formapp.js"></script>

<link rel="stylesheet" href="../style.css" />
</head>

<body ng-controller="UserController as usersCtrl">

<h3>User Information</h3>
<div ng-repeat="user in usersCtrl.mUsers">
<p><ul>
<li>{{user.name}}</li>
<li>{{user.age}}</li>
<li>{{user.occupation}}</li>
</ul></p>
</div>

<form-Directive></form-Directive>

</body>

</html>

app.js

(function(){

var app = angular.module('training',['form']);


app.controller('UserController',function(){

this.mUsers = users;
});

var users = [{
name:"michael",
age:"27",
occupation:"business"
},{
name:"john",
age:"25",
occupation:"police"
}];

})();

formapp.js

(function(){
var app = angular.module("form",[]);
app.directive('formDirective', function(){
return{
restrict: 'E',
templateUrl: 'user-form-directive.html',
controller:function(){
this.newUser = {};

this.addUser = function(){
users.push(this.newUser); //<-- users is not defined
this.newUser = {};
};
},
controllerAs: 'formCtrl'
};
});
})();

最佳答案

您可以将 mUsers 作为属性传递给您的元素指令 - formDirective

index.html

<form-Directive users='mUsers'></form-Directive>

formapp.js

(function(){
var app = angular.module("form",[]);
app.directive('formDirective', function(){
return{
restrict: 'E',
templateUrl: 'user-form-directive.html',
scope: {
users: '='
},
controller:['$scope', function($scope){
this.newUser = {};

this.addUser = function(){
$scope.users.push(this.newUser); //<-- users is not defined
this.newUser = {};
};
}]
};
});
})();

关于javascript - AngularJS无法访问变量差异文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940319/

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