簡體   English   中英

Angular.js-指令和服務通信

[英]Angular.js - directive and service communication

jsbin: http ://jsbin.com/oworoz/1/edit

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <meta charset=utf-8 />
        <title>JS Bin</title>
    </head>
    <body ng-app="deeme">
        <modal ></modal>
        <script type="text/ng-template" id="templ1" >Bu birinci template</script>
        <script type="text/ng-template" id="templ2" >Bu ikinci template</script>
        <script type="text/ng-template" id="templ3" >Bu üçüncü template</script>

        <button ng-controller="b1" ng-click="update()">templ1</button>
        <button ng-controller="b2" ng-click="update()">templ2</button>
        <button ng-controller="b3" ng-click="update()">templ3</button>

        <script type="text/javascript">
            angular.module ("deeme", [])
            .factory("serv", function(){
                return {
                    data: {
                        template: "templ1"
                    }
                }

            })
            .controller("b1", ["$scope", "serv", function($scope, serv){
                $scope.update = function(){
                    serv.data.template = "templ1";
                }
            }])
            .controller("b2", ["$scope", "serv", function($scope, serv){
                $scope.update = function(){
                    serv.data.template = "templ2";
                }
            }])
            .controller("b3", ["$scope", "serv", function($scope, serv){
                $scope.update = function(){
                    serv.data.template = "templ3";
                }
            }])
            .directive("modal", ["serv", function(serv){
                return {
                    restrict: "E",
                    template: "<div ng-include='currTempl'></div>",
                    replace: true,
                    link: ["$scope", function($scope){
                      $scope.currTempl = serv.data.template; 
                      alert($scope.currTempl);
                        $scope.$watch(serv.data.template, function(newVal, oldVal){
                            $scope.currTempl = newVal; 
                        });
                    }]
                }
            }])
        </script>
    </body>
</html>

我正在嘗試制作一個類似於模式的容器,每次單擊不同的按鈕時,它將顯示不同的模板。 為此,我創建了三個按鈕和相關的控制器控制器,更新了服務提供的共享變量和將讀取共享變量的指令,並在更改時根據共享變量的值更新給定元素的內容。 。

但是我無法使指令生效。 我究竟做錯了什么?

不需要$ watch。 只需將指令范圍屬性分配給serv.data

.directive("modal", function(serv){
    return {
        restrict: "E",
        template: "<div ng-include='data.template'></div>",
        replace: true,
        link: function($scope){
            $scope.data = serv.data; 
        }
    }
})

當您的控制器更新服務屬性時,ng-include將引起注意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM