Angularjs 如何捕获正在监视的$scope模型对象的值
在我的angular应用程序中,我有一个模型对象“selectedDcName” 此模型的值与下拉选择中的选择相关联 我试图观察值的变化,我需要知道新值实际上是什么 如何正确地做到这一点 以下是我的html标记:Angularjs 如何捕获正在监视的$scope模型对象的值,angularjs,Angularjs,在我的angular应用程序中,我有一个模型对象“selectedDcName” 此模型的值与下拉选择中的选择相关联 我试图观察值的变化,我需要知道新值实际上是什么 如何正确地做到这一点 以下是我的html标记: <isteven-multi-select input-model="dcNames" output-model="s
<isteven-multi-select
input-model="dcNames"
output-model="selectedDcName"
button-label="icon name"
item-label="icon name maker"
tick-property="ticked"
selection-mode="single"
>
</isteven-multi-select>
与我的期望相反,“名字”一点也没有
我该如何正确地执行此操作?
这是我为同样目的编写的代码。它将所有职责分解为一个服务、一个数据控制器和一个dom操作指令
看看有多简单!:
;(function AngularSelectbox() {
"use strict";
var SelectBox = angular.module('selectbox', []);
SelectBox.service('SelectboxUtils', function() {
this.getStates = function() {
var statesOpts = {
// $http.post(..., function())...
"options": ['Florida', 'Georgia', 'Alabama', 'New York'],
};
return statesOpts;
};
}).controller('statesDataCtrl', function($scope, SelectboxUtils) {
$scope.selectbox = {};
$scope.selectbox.optionsVisible = false;
$scope.selectbox.selectorSrc = 'http://placehold.it/20x20/';
$scope.selectbox.options = SelectboxUtils.getStates().options;
$scope.selectbox.placeholder = 'Please make a selection';
$scope.selectbox.selected = $scope.selectbox.placeholder; // Always will pull the first option as the default
}).directive('selectbox', function() {
return {
restrict: 'A',
link: function($scope, elm) {
$scope.activateSelection = function(selection, index) {
$scope.selectbox.selected = selection;
$scope.selectbox.selectedIndex = index;
};
$scope.toggleOpts = function() {
$scope.selectbox.optionsVisible = !$scope.selectbox.optionsVisible;
};
}
};
});
})();
下面是我如何解决这个问题的:
$scope.$watch(function(scope) {return $scope.selectedDcName },
function(newValue, oldValue) {
if(newValue[0]){
console.log('new value: ' + newValue[0].name);
}
if(newValue[0]){
$scope.$parent.selectedName = newValue[0].name;
}
}
);
还值得注意的是,通过像这样拆分Angular模块,您可以重用从未想过可以重用的代码。。。一次又一次在最近开发的一个小型应用程序中,我使用了一个TrackActiveSelection服务十几次,用于导航菜单、图像滑块和手风琴。AngularJS真的是另一回事。这很好!然而,在我的应用程序中,我使用的是第三方“isteven multi-select”,它将其选择输出到名为selectedDcName的模型。我试图弄清楚,一旦实际值发生变化,如何捕捉它。这将适用于正在监视的任何其他模型。与$watch关联的函数可以启动,但我不知道如何获取更改后的值啊,我知道我以为是您自己定制了istevenselect。我希望我能提供更多的帮助,我相信其他人已经为你准备好了!我想说的是,与控制器中的$watch(几乎总是一个no-no)不同,我将使用本教程中的ngChange
$scope.$watch(function(scope) {return $scope.selectedDcName },
function(newValue, oldValue) {
if(newValue[0]){
console.log('new value: ' + newValue[0].name);
}
if(newValue[0]){
$scope.$parent.selectedName = newValue[0].name;
}
}
);