2014-02-28 129 views
1

我是新的角度世界,我有負載加載內部perticular div的HTML的功能,然後控制器得到初始化。我想讓控制器內部的單個變量可用,所以想知道是否可以將該變量從控制器外部分配給範圍。如何從控制器外部傳遞一個值到範圍?

//controller 
var cntlrs = angular.module('MyModule'); 

cntlrs.controller('ControllerTest', function ($scope, $http) { 
    //want to have var available here from $scope 
}); 


//accessing scope from outside 
var appElmt = document.querySelector('[ng-app=MyApp]'); 
var $scope = angular.element(appElmt).scope(); 
var customer = "New Customer"; 

//how can I set customer value inside scope? 
+0

我想訪問的變量不是模型的一部分。它有可能在那裏嗎? – updev

+0

你可以發佈你的html和/或創建一個plunkr或jsfiddle嗎? – JamesClevenger

回答

0

是,從控制器外,你可以定位你的角度控制器中的一個元素:

var scope = angular.element("#YourElementID").scope(); 

現在你將有機會獲得一切的scope(就像如果你使用$scope

+0

是的,但如何從那裏分配新的變量和值? – updev

1

我建議閱讀角度文檔更多。 $ scope是你的模型(或者可能術語ViewModel更合適)。

要獲得值到您的控制器,我會推薦一個工廠或服務。可以在工廠調用setCustomer,然後其他控制器可以使用getCustomer來查看該值。

var mod = angular.module('MyModule', []); 

mod.factory("CustomerFactory", function() { 
    var customer; 
    return { 
     getCustomer: function() { 
      return custData; 
     } 
     setCustomer: function (custData) { 
      customer = custData; 
     } 
    } 
}); 

mod.controller("TestController", function ($scope, $http, CustomerFactory) { 
    $scope.customer = CustomerFactory.getCustomer(); 
} 

也可能是更好,如果你沒有參考的角度之外$範圍(即從angular.element(...)。範圍())。我不知道你想要解決什麼問題,但是從上面的代碼看來,所有的邏輯都可以放在控制器中。

0

我決定像這樣工作,它似乎是好的!它不需要很大的努力,只有枯燥的部分是在模板中,你需要經常使用vars.somepropertyormethod

//an outside var that keeps all the vars I want in my scope 
var vars = { 
    val1: 1, 
    val2: "dsfsdf", 
    val3: function() {return true;} 
} 


//and here I set the controller's scope to have ONLY vars and nothing else: 
angular.module('myModule', []) 
    .controller('myControllerOpenToTheWorld', function($scope) { 
     $scope.vars = vars; 
    }); 

有了這個,我可以設置vars.anyproperty從任何地方我想要的。訣竅是,真正的值都包裹的物體裏面,所以只要你不重新分配包裝vars,您可以從外部和內部訪問:

//change val2 
vars.val2 = "new value changed from outside"; 

在標記,它會這樣的工作:

<div>{{vars.val1}}</div> 
<div ng-if:"vars.val3()">{{vars.val2}}</div> 
相關問題