yelliver yelliver - 1 year ago 90
AngularJS Question

angular change property of scope by reference from ng-init

I have an input and a button, I want when the button clicked, the value of input will be changed:

<input type="text" ng-model='myModel'>
<button ng-click="changeMyModel()">my button</button>

in the controller:

$scope.changeMyModel = function () {
$scope.myModel = 'new value';

It works, but when I want to pass myModel into changeMyModel() function:

<input type="text" ng-model='myModel'>
<button ng-click="changeMyModel(myModel)">my button</button>

$scope.changeMyModel = function (myModel) {
myModel = 'new value';

It does not work

I really want pass a property into a function because when I use ng-repeat, each loop, the model is different, and I can not declare n var in scope for n elements of an array when loop (I have $sope.objects):

<div ng-repeat="object in objects">
<input type="text" ng-model='object'>
<button ng-click="changeMyModel(object )">my button</button>

Answer Source

In ng-repeat, it's OK to modify object, you could do something like this:

<div class="test" ng-controller="Ctrl">
  <div ng-repeat="task in tasks">
   <button ng-click="removeTask(task);">{{}}</button>

In controller:

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

function Ctrl($scope) {
  $scope.tasks = [{id:1,'name':'test1'}, {id:2,'name':'test2'}, {id:3,'name':'test3'}];

  $scope.removeTask = function(task){ = 'abc';

Or you could pass your item index in the list to your function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download