在 Angular js 中,html 是否可以访问 $scope 中未定义的函数?
例如
这是 Controller
function TestController($location, $scope){
var vm = this;
vm.test2 = test2
$scope.test1 = function(){
console.log("testing");
};
function test2(){
console.log("what is going on");
}
}
这是有效的 html
<div ng-controller="TestController" id="whatup">
<form ng-submit="test1()">
<input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="email"></input>
<input type="submit">
</form>
</div>
如果我将 test1()
更改为 test2()
,代码将不再有效,这是否有原因?
我是否必须通过其他方式公开test2()
,例如在路由中定义它?
function config($routeProvider){
$routeProvider.when('/test', {
controller: 'TestController',
controllerAs: 'vm',
templateUrl: 'templates/test.html'
}).otherwise('/');
}
最佳答案
一个不错的选择是将 test2
函数直接创建到 Controller 变量中:
function TestController($location, $scope, Authentication){
var vm = this;
$scope.test1 = function(){
console.log("testing");
};
vm.test2 = function (){
console.log("what is going on");
};
}
您还可以像这样调整 html:
<div ng-controller="TestController as vm" id="whatup">
<form ng-submit="vm.test2()">
<input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="email"></input>
<input type="submit">
</form>
</div>
关于javascript - Angular ng-submit 只允许作用域内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32154411/