Angular - 如何通过$ scope中的函数更改$ scope属性值

时间:2015-07-03 09:59:38

标签: javascript angularjs

如何通过$ scope中的函数更改$ scope属性值?

HTML,

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

角,

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;
    };
});

结果,

Hi

我的期望,

Hello World

或者,我可以通过函数向$ scope添加属性吗?

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> 

我一无所获......

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

好的,$scope.greeting$scope.sayHello函数中定义,因此在greeting函数执行之前没有名为sayHello()的范围属性。

执行功能,greeting

中将显示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

无关紧要returnnot return

在该函数内

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

首先$scope.greeting分配值,然后在此之后将有$scope.greeting到html。

答案 1 :(得分:2)

您无需返回作业,只需设置$scope属性即可。

将您的方法更新为:

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

答案 2 :(得分:1)

你们所要做的就是:

HTML,

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

角,

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;
    };
});

我希望它能解决你的问题