如何通过$ 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>
我一无所获......
有什么想法吗?
答案 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();
});
无关紧要return
或not 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;
};
});
我希望它能解决你的问题