Reputation: 2692
I tried to implement for first time the controller as syntax and I face a problem where my function doesn't change the controller variable which I pass from the template. Instead it understands the parameter as a local variable. This wouldn't happen if I use $scope.
Here's my controller.
angular
.module('app')
.controller('baseCtrl', baseCtrl);
function baseCtrl() {
base = this;
base.myVar = 'string_1';
base.myFunction = myFunction;
function myFunction(value) {
value = 'string_2"';
}
}
Here's my template.
<div ng-controller="baseCtrl as base">
<button ng-click="base.myFunction(base.myVar)">Button</button>
</div>
After click base.myVar should change from "string_1" to "string_2" but this doesn't happen.
Does somebody know how I could figure it out ?
Upvotes: 1
Views: 91
Reputation: 2692
I finally figured out what was wrong. The problem is that the variable I pass is primitive. The solution is to change my variables to from primitive to objects.
So in my case the solution is:
base.myVar = {
val: "string_1"
};
function myFunction(value) {
value.val = "string_2";
};
Upvotes: 0
Reputation: 326
You have to assign
base.myVar = 'string"';
in myFunction and define module app like this:-
angular.module('app',[]);
This is the modified code that will work.
angular
.module('app', [])
.controller('baseCtrl', baseCtrl);
function baseCtrl() {
var base = this;
base.myVar = 'string_1';
base.myFunction = myFunction;
function myFunction(value) {
base.myVar = 'string_2"';
}
}
Upvotes: 1
Reputation: 1233
it can be done like this , do some changes in your code
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>
Upvotes: 1