简体   繁体   English

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

[英]Angular - How to change the $scope property value via the function in the $scope

How can I change the $scope property value via the function in the $scope? 如何通过$ scope中的函数更改$ scope属性值?

html, 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? 或者,我可以通过函数将属性添加到$ scope吗?

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

html, HTML,

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

I get nothing... 我什么都没有

Any ideas? 有任何想法吗?

ok, $scope.greeting is defined inside the $scope.sayHello function so there is no scope property called greeting until sayHello() function execute. 好的, $scope.greeting是在$scope.sayHello函数中定义的,因此直到sayHello()函数执行之前,没有称为greeting作用域属性。

execute the functin and greeting will be available in the HTML 执行functin并在HTML提供greeting

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 无论return还是not return任何东西

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. 第一$scope.greeting分配值,那么在此之后还会有有$scope.greeting到HTML。

You don't need to return the assignment, simply set the $scope property and it will work. 您无需返回分配,只需设置$scope属性即可。

Update your method to: 将您的方法更新为:

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

You all need to do is: 您需要做的是:

html, 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 我希望它能解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM