我是AngularJs的新人。我刚开始学习依赖概念。但是当app.js
和formapp.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'
};
});
})();
答案 0 :(得分:3)
您可以将 mUsers 作为属性传递给元素指令 - formDirective 。
<强>的index.html 强>
///storage/0/emulated/...
<强> formapp.js 强>
<form-Directive users='mUsers'></form-Directive>