2014-07-14 84 views
1

this ng-book JSBin中,由於原型繼承,$scope.$watch()解析爲$rootScope.$watch()

我們是否可以在控制器內部明確注入$rootScope,以便$scope與控制器內的$rootScope相同,而無需通過原型繼承?

複製代碼在這裏以供參考:

// open this example and type person.name into the test field 
    angular.module('myApp', []) 
    .controller('MyController', 
    ['$scope', '$parse', function($scope, $parse) { 

     $scope.person = { 
     name: "Ari Lerner" 
     }; 

     $scope.$watch('expr', function(newVal, oldVal, scope) { 
     if (newVal !== oldVal) { 
      // Let's set up our parseFun with the expression 
      var parseFun = $parse(newVal); 
      // Get the value of the parsed expression, set it on the scope for output 
      scope.parsedExpr = parseFun(scope); 
     } 
     }); 
    }]); 
+0

確保它可以注射,也不會是'與$ scope'不過,'$ scope'仍將是根 – charlietfl

+0

聖胡安不錯,但怎麼個孩子嗎? – Mahesha999

回答

2

只需注入它與$scope$parse相同的方式,就可以在控制器內部訪問$ rootScope上定義的任何內容。

app.controller('MyController', ['$scope', '$parse', '$rootScope', 
    function($scope, $parse, $rootScope) { 

     $rootScope.foo(); 

     console.log($rootScope.bar); 
    } 
]); 

1

如果您打算使用rootScope得很厲害,它有一個供應商,就像scope一樣。將'$rootScope'包括到您的控制器中,就像'$scope'一樣。

還有$scope$parent屬性可以派上用場,但是如果被濫用,它往往會使代碼更少維護。特別是當多個作用域嵌套時,因爲您需要遍歷整個層次結構。