angularjs
  • angularjs-directive
  • angularjs-scope
  • 2014-02-16 72 views 0 likes 
    0

    LIVE DEMOAngularJS指令:为什么观察者没有被触发?

    考虑以下两条指令:

    JS:

    angular.module("Directives", []).directive("action", function($compile) { 
        return { 
        restrict: 'A', 
        scope: { 
         action: '=' 
        }, 
        link: function(scope, element) { 
         scope.showDialog = false; 
    
         var template = "<span dialog='showDialog'>Dialog</span>"; 
    
         element.append($compile(template)(scope)).on('click', function() { 
         console.log("Setting showDialog to true"); 
         scope.showDialog = true; 
         }); 
        } 
        }; 
    }).directive("dialog", function() { 
        return { 
        restrict: 'A', 
        scope: { 
         dialog: '=' 
        }, 
        link: function(scope, element) { 
         element.hide(); 
    
         scope.$watch('dialog', function(newValue) { 
         console.log("dialog changed to " + newValue); // Not called on button click 
         }); 
        } 
        }; 
    }); 
    

    HTML:

    <button action>Click Here</button> 
    

    你能解释一下为什么设置actionshowDialog不会触发dialog“看守人?

    +0

    其实,当你点击按钮 - 指令'对话'中的'对话'不会改变 - 看起来不是绑定正确 - 也许是因为$ compile中的作用域与action-> link中的作用域不同?但我不知道如何解决这个问题。 –

    回答

    2

    .on()是包含在Angular的jqLit​​e中的jQuery方法。附加的事件处理程序中的代码居住的角度之外,所以你需要使用$apply

    $适用()用于从 角框架之外的角度来执行的表达式。 (例如,来自浏览器DOM事件, setTimeout,XHR或第三方库)。因为我们正在调用 角度框架,我们需要执行适当的范围生命周期 异常处理,执行手表。

    例如:

    element.append($compile(template)(scope)).on('click', function() { 
        scope.$apply(function() { 
        console.log("Toggling showDialog"); 
        scope.showDialog = !scope.showDialog; 
        }); 
    }); 
    

    演示:http://jsbin.com/guziwamu/4/edit

    0

    我做了一些改变写它的更常见的方法和我移动element.hide();在$表登记后,它能正常工作

    app.directive("action", function ($compile) { 
    function link(scope, element, attrs) {  
        var template = "<span dialog='showDialog'>Dialog</span>"; 
    
        element.append($compile(template)(scope)).on('click', function() { 
         console.log("Setting showDailog to true"); 
         scope.showDailog = !scope.showDailog; 
        }); 
    } 
    
    return { 
        link: link 
    }; 
    }); 
    
    app.directive("dialog", function ($compile) { 
    function link(scope, element, attrs) { 
    
        scope.$watch(attrs.dialog, function (newValue) {    
         console.log("dialog changed to " + newValue); // Not called on button click 
        }); 
    
        element.hide(); 
    } 
    
    return { 
        link: link 
    }; 
    }); 
    

    控制器:

    app.controller('MyController', function ($scope) { 
    
    $scope.showDailog = false; 
    }); 
    

    应用JS:

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

    HTML:

    <button action>Click Here</button> 
         Show dialog: <input data-ng-model="showDailog"> 
    
    +0

    你能否提供一个可用的jsbin? –

    相关问题