angularjs - AngularJS 中 Controller 和指令之间的共享范围

标签 angularjs angularjs-directive angularjs-scope

我创建了一个指令来包装 jQuery 插件,并将插件的配置对象从 Controller 传递到该指令。 (作品)

配置对象中有一个我想在事件上调用的回调。 (作品)

在回调中,我想修改 Controller $scope 上的一个属性,但这不起作用。 Angular 无法识别该属性由于某种原因已更改,这使我相信回调中的 $scope 与 Controller 的 $scope 不同。我的问题是我不知道为什么。

有人能指出我正确的方向吗?

<小时/>

Click here for Fiddle

<小时/>

app.js

var app = angular.module('app', [])
    .directive('datepicker', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                // Uncommenting the line below causes
                // the "date changed!" text to appear,
                // as I expect it would.
                // scope.dateChanged = true;

                var dateInput = angular.element('.datepicker')

                dateInput.datepicker(scope.datepickerOpts);

                // The datepicker fires a changeDate event
                // when a date is chosen. I want to execute the
                // callback defined in a controller.
                // ---
                // PROBLEM: 
                // Angular does not recognize that $scope.dateChanged
                // is changed in the callback. The view does not update.
                dateInput.bind('changeDate', scope.onDateChange);
            }
        };
    });

var myModule = angular.module('myModule', ['app'])
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.dateChanged = false;

        $scope.datepickerOpts = {
            autoclose: true,
            format: 'mm-dd-yyyy'
        };

        $scope.onDateChange = function () {
            alert('onDateChange called!');

            // ------------------
            // PROBLEM AREA:
            // This doesnt cause the "date changed!" text to show.
            // ------------------
            $scope.dateChanged = true;

            setTimeout(function () {
                $scope.dateChanged = false;
            }, 5000);
        };
    }]);

html

<div ng-controller="MyCtrl">
    <p ng-show="dateChanged">date changed!</p>
    <input type="text" value="02-16-2012" class="datepicker" datepicker="">
</div>

最佳答案

您的演示中存在许多范围问题。首先,在 dateChange 回调中,即使函数本身是在 Controller 内部声明的,回调中 this 的上下文也是引导元素,因为它位于引导处理程序中。

每当您从第三方代码中更改 Angular 范围值时, Angular 都需要使用$apply来了解它。通常最好将所有第三方范围保留在指令内。

一种更有 Angular 的方法是在输入上使用ng-model。然后使用 $.watch 对模型进行更改。这有助于将 Controller 内的所有代码保持在 Angular 上下文中。在任何 Angular 应用程序中很少不在任何表单控件上使用 ng-model

 <input type="text"  class="datepicker" datepicker="" ng-model="myDate">

指令内:

dateInput.bind('changeDate',function(){
      scope.$apply(function(){
         scope[attrs.ngModel] = element.val()
      });
});

然后在 Controller 中:

$scope.$watch('myDate',function(oldVal,newVal){ 
       if(oldVal !=newVal){
           /* since this code is in angular context will work for the hide/show now*/
            $scope.dateChanged=true;
             $timeout(function(){
                   $scope.dateChanged=false;
              },5000);
        }        
});

演示:http://jsfiddle.net/qxjck/10/

编辑 如果您想在多个元素上使用此指令,则应更改的另一项是删除 var dateInput = angular.element('.datepicker')在页面中。在指令中使用它是多余的,其中 element 已经是 link 回调中的参数之一,并且是特定于实例的。将 dateInput 替换为 element

关于angularjs - AngularJS 中 Controller 和指令之间的共享范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15605931/

相关文章:

javascript - 使用后退按钮移动单页应用程序 AngularJS

angularjs - ng-pattern 验证不起作用

javascript - Angular : select ng-model programmatically changed but ng-change event doesn't fire

javascript - 当路由到特定路由 Angularjs 时运行函数?

javascript - 使用 AngularJS/MVC5 在列表页面上实现搜索

javascript - 使用 AngularJS 扩展表格内容

javascript - Angular : watch for filtered value in directive

javascript - angularjs:正在监视的变量不断恢复为旧值

javascript - 使用 Angular.js 动态添加表格列

javascript - 如何在不可见的 Angular js中应用过滤器?