我第一次尝试将 Controller 作为语法来实现,但我遇到了一个问题,即我的函数不会更改我从模板传递的 Controller 变量。相反,它将参数理解为局部变量。如果我使用 $scope,就不会发生这种情况。
这是我的 Controller 。
angular
.module('app')
.controller('baseCtrl', baseCtrl);
function baseCtrl() {
base = this;
base.myVar = 'string_1';
base.myFunction = myFunction;
function myFunction(value) {
value = 'string_2"';
}
}
这是我的模板。
<div ng-controller="baseCtrl as base">
<button ng-click="base.myFunction(base.myVar)">Button</button>
</div>
点击后 base.myVar 应该从“string_1”变为“string_2”,但这并没有发生。
有人知道我怎么弄明白吗?
最佳答案
可以这样做,对代码做一些修改
angular
.module('app',[])
.controller('baseCtrl',function(){
var base = this;
base.myVar = 'string_1';
base.myFunction = myFunction;
function myFunction(value) {
value = 'string_2"';
base.myVar = value
alert(value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="baseCtrl as base">
<input type="text" ng-model="base.myVar"/>
<button ng-click="base.myFunction(base.myVar)">Button</button>
</div>
关于javascript - Controller 作为语法不会改变 Controller 的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391304/