2013-06-04 28 views
2

比方说,我有这样的事情:

<div ng-app="myApp"> 
    <div ng-controller="myCtrl"> 
     {{foo}} 
     <button ng-click="bindToMe" /> 
    </div> 
    <div ng-controller="anotherCtrl"> 
     {{foo}} 
     <button ng-click="noBindToMeInstead" /> 
    </div> 
</div> 

<!-- yes its outside of ng-app --> 
<div id="tempZone"> 
    <input type="text" ng-model="foo" /> 
</div> 

我想作的就是用#tempZone编译/数据绑定,如果它是的一部分具体范围。

喜欢的东西:

var myApp = angular.module('myApp'); 
myApp.controller('myCtrl', function($scope){ 
    $scope.foo = "init1"; 
    $scope.bindToMe = function(){ 
     var tempZone = document.getElementById('tempZone'); 
     $scope.$MAGICBINDMETHOD(tempZone); 
    }; 
}); 
myApp.controller('anotherCtrl', function($scope){ 
    $scope.foo = "init2"; 
    $scope.noBindToMeInstead = function(){ 
     var tempZone = document.getElementById('tempZone'); 
     $scope.$MAGICBINDMETHOD(tempZone); 
    }; 
}); 

我想这让我可以写一个模态窗口服务,允许加载的模板与调用该模式的范围进行交互。到目前为止,我没有看到这个工作的例子。将dom元素绑定到可能的范围?

回答

4

显然答案非常简单。

$scope.$MAGICBINDMETHOD(tempZone); 

只是

$compile(tempZone)($scope); 

,并对其做。

2

我会使用一个控制器和范围为您的常见tempZone,使用服务进行数据共享(用于输入),并$从一个控制器发出'bindToMe'事件,以指示另一个控制器停止监听更改。

<div ng-app="myApp"> 
    <div ng-controller="myCtrl"> 
     {{foo}} 
     <button ng-click="bindToMe()" /> 
    </div> 
    <div ng-controller="anotherCtrl"> 
     {{foo}} 
     <button ng-click="bindToMe()" /> 
    </div> 

<!-- no its not outside of ng-app --> 
    <div id="tempZone" ng-controller="tempZoneCtrl"> 
     <input type="text" ng-model="myService.foo" /> 
    </div> 
</div> 

线和控制器的东西:

angular.module('myApp') 
.controller('myCtrl', function($scope, myService){ 
    $scope.foo = "init1"; 
    $scope.$root.$on("bindToMe", function(event) { 
     if (event.target != $scope) releaseBinding(); 
    }; 
    $scope.bindToMe = function(){ 
     $scope.$emit("bindToMe"); 
    }; 
}) 
.controller('anotherCtrl', function($scope, myService){ 
    $scope.foo = "init2"; 
    $scope.$root.$on("bindToMe", function(event) { 
     if (event.target != $scope) releaseBinding(); 
    }; 
    $scope.bindToMe = function(){ 
     $scope.$emit("bindToMe"); 
    }; 
}) 
.controller('tempZoneCtrl', function($scope, myService){ 
    $scope.$watch('foo', function(newV) { myService.foo = newV; }); 
}) 
.service('myService', function() { 
    return {}; 
}); 

你的模态将独立,关于值的结合的任何其他控制器上,它只是依赖于一个单独服务(这实际上是数据传递的正确工具)。

此外,你会想检查angular-ui的$对话框提供程序(http://angular-ui.github.io/bootstrap/#/dialog)。他们正在重写twitter-bootstrap javascript以使其更加友好。

+1

对不起,增加了复杂性。但我不一定知道我正在观察的变量的名称。我正在尝试创建一个可以绑定到任何范围并使用任何模板的通用服务。 +1为有帮助。 – Fresheyeball