我对Angular很新,但我试图从另一个控制器(指令的父包装控制器)内的指令控制器访问一个名为 hour 的属性。
以下是我如何设置指令及其控制器:
(function () {
angular.module("datePicker", [])
.directive("datePicker", function () {
return {
restrict: "E",
scope: {
ctrl: '=ctrl'
},
templateUrl: "app/views/datepicker.html"
};
})
.controller('datePickerController', function ($scope) {
this.min = "";
this.hour = "";
this.minutes = [];
this.hours = [];
let i = 0;
for (i; i < 60; i++) {
let time = "";
if (i <= 9) {
time = "0" + i;
} else time = i;
this.minutes.push(time);
if (time <= 23) {
this.hours.push(time);
}
}
$scope.somechange = function (v) {
alert(v);
$scope.hour = v;
$scope.$parent.printFrom = "It changed";
}
});
})();
这是指令的实现:
<div ng-controller="datePickerController as ctrl">
<md-input-container>
<label>Hour</label>
<md-select ng-change="somechange(ctrl.hour)" ng-model="ctrl.hour">
<md-option ng-repeat="hour in ctrl.hours" ng-value="hour">
{{ hour }}
</md-option>
</md-select>
</md-input-container>
</div>
如何从“父母”调用它:
<div>
<date-picker ctrl="from"></date-picker> {{ from.today | date:'short' | split:' ':0}}, {{ $scope.hour }}
</div>
正如您所看到的,我正在尝试从datepicker的范围访问 hour 属性,但我无法访问它(或者至少它没有更新)。
我可以在其alert
事件中调用的ng-change
中看到它很好,但我似乎无法在父母的范围内找到它...
答案 0 :(得分:1)
您必须在父对象上添加属性小时。
控制器和指令代码:
var app = angular.module('datepicker', []);
app.controller('ParentController', function($scope) {
$scope.parent = {};
});
app.directive('datePicker', function () {
return {
restrict: 'E',
scope: {
parent: '='
},
templateUrl: 'app/views/datepicker.html'
};
})
.controller('datePickerController', function ($scope) {
this.min = '';
this.hour = '';
this.minutes = [];
this.hours = [];
let i = 0;
for (i; i < 60; i++) {
let time = '';
if (i <= 9) {
time = '0' + i;
} else time = i;
this.minutes.push(time);
if (time <= 23) {
this.hours.push(time);
}
}
$scope.somechange = function (v) {
alert(v);
$scope.parent.hour = v;
$scope.$parent.printFrom = 'It changed';
}
});
将指令创建为html元素:
<date-picker parent="parent"></date-picker>
<p>{{parent.hour}}</p>