gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:26:13 31 4
gpt4 key购买 nike

我创建了一个指令来包装 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com