2017-01-05 85 views
-2

首先请原谅,如果这没有任何意义。

我有一个根的范围与在同一个控制器分配两个不同的值,现在我想使用根范围来打印这两个值.....我如何才能做到这一点

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

 
app.controller('MainCtrl', function($scope,$rootScope) { 
 
    $rootScope.name = 'hello'; 
 
    $rootScope.name="world"; 
 
});
<!DOCTYPE html> 
 
<html ng-app="plunker"> 
 

 
    <head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 

 
    
 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script> 
 
    
 
    </head> 
 

 
    <body ng-controller="MainCtrl"> 
 
    <p>{{name}}</p> 
 
    </body> 
 

 
</html>

从上面我想打印的hello world ......

+1

作为一个方面,你应该在这里更喜欢'$ scope'。当不需要时避免使用'$ rootScope'。 – Mistalis

+0

@mistails即使你使用$ scope,你也只会得到“world” –

+0

这个评论并不是为了**回答**的问题,而是要**警告你**使用'$ rootScope'。 – Mistalis

回答

0

当你调用$ rootScope.name =“世界”要覆盖第一个值;,我建议你做一个反而像这样;

$rootScope.helloWorld = {hello: "hello", world: "world"}; 

在html中;

<p>{{helloWord.hello}} {{helloWorld.world}}</p> 
+0

不起作用。应该是'

{{$ rootScope.helloWord.hello}} {{$ rootScope.helloWorld.world}}

'。 – Mistalis

0

你想要做什么是

$rootScope.name = "hello"; 
$rootScope.name += " world"; 

在代码中,你只是来取代值。

+0

可能是你的正确....当然它喜欢取代我错过了,但让我们看看我们有任何其他的选择 –

+0

嗯,这是这个解决方案(这仍然没有任何意义,或只是做$ rootScope.hello = “hello”; $ rootScope.world =“world”;并在{{hello}} {{world}}视图中显示它们 – Roux

+0

我知道这种方式,但血腥的面试官让我空白,我现在正在狩猎 –

相关问题