0

How can I change the $scope property value via the function in the $scope?

html,

<div ng-app="myApp" ng-controller="SimpleController">{{greeting}}</div>

angular,

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

app.controller('SimpleController', function($scope) {
    $scope.name = "World";
    $scope.greeting = "Hi";
    $scope.sayHello = function() {
        return $scope.greeting = "Hello " + $scope.name;
    };
});

Result,

Hi

What I expect,

Hello World

Or, can I add properties to $scope via function?

app.controller('SimpleController', function($scope) {
    $scope.name = "World";
    $scope.sayHello = function() {
        return $scope.greeting = "Hello " + $scope.name;
    };
});

html,

<div ng-app="myApp" ng-controller="SimpleController">{{greeting}}</div> 

I get nothing...

Any ideas?

3
  • 1
    where you call the function sayHallo Commented Jul 3, 2015 at 10:01
  • can I call it like this - <div ng-app="myApp" ng-controller="SimpleController">{{sayHello(); greeting}}</div>? Commented Jul 3, 2015 at 10:04
  • 1
    ya sure you call like this get call sayhello refer to my answer Commented Jul 3, 2015 at 10:13

3 Answers 3

2

ok, $scope.greeting is defined inside the $scope.sayHello function so there is no scope property called greeting until sayHello() function execute.

execute the functin and greeting will be available in the HTML

app.controller('SimpleController', function($scope) {
    $scope.name = "World";
    $scope.sayHello = function() {
        return $scope.greeting = "Hello " + $scope.name;
    };

    //execute the function after execution greeting will be available in the html
    $scope.sayHello();
});

Example

it doesn't matter return or not return anything

inside that function

 return $scope.greeting = "Hello " + $scope.name;

first $scope.greeting assign the value so then after this there will have the $scope.greeting to the html.

Sign up to request clarification or add additional context in comments.

Comments

2

You don't need to return the assignment, simply set the $scope property and it will work.

Update your method to:

$scope.sayHello = function() {
    $scope.greeting = "Hello " + $scope.name;
};

Comments

1

You all need to do is:

html,

<div ng-app="myApp" ng-controller="SimpleController">{{sayHello()}}</div>

angular,

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

app.controller('SimpleController', function($scope) {
    $scope.name = "World";
    $scope.greeting = "Hi";
    $scope.sayHello = function() {
        return $scope.greeting = "Hello " + $scope.name;
    };
});

I hope it will solve your problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.