我在项目中使用Angular材质元素.我想从
Java Script更新材料输入值.值正确绑定到作用域但不在输入框中更新.
我为此创建了一个JSFiddle
HTML
<div data-ng-app="testApp" data-ng-cloak>
<div id='appCtrl' data-ng-controller="testCtrl">
<button id="button">
Update value in Dialog
</button>
<span>Value: {{brokenLink}}</span>
</div>
</div>
ANGULAR
var testApp = angular.module('testApp', ['ngMaterial']);
testApp.controller('testCtrl', function ($scope, $mdDialog, $mdMedia) {
$scope.brokenLink = "Initial Value";
$scope.showDialog = function(ev) {
var useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && $scope.customFullscreen;
$mdDialog.show({
controller: DialogController,
template: "<md-dialog aria-label='testArea' ng-cloak flex='66'><form><md-toolbar><div class='md-toolbar-tools'><h2>Add Redirection Link</h2><span flex></span><md-button class='md-icon-button' ng-click='cancel()'><md-icon md-font-icon='fa-times-circle' aria-label='Close dialog' class='fa fa-2x'></md-icon></md-button></div></md-toolbar><md-dialog-content layout='column' style='min-width: 500px'><div class='md-dialog-content'><md-input-container class='md-block'><md-icon md-font-icon='fa-chain-broken' class='fa fa-2x'></md-icon><input id='broken-link' ng-model='brokenLink' type='text' placeholder='Broken Link (required)' ng-required='true'></md-input-container></div></md-dialog-content><md-dialog-actions layout='row'><md-button ng-click='answer()'>Cancel</md-button><md-button ng-click='answer()' style='margin-right:20px;'>Add</md-button></md-dialog-actions></form></md-dialog>",
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
fullscreen: useFullScreen
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
$scope.$watch(function() {
return $mdMedia('xs') || $mdMedia('sm');
}, function(wantsFullScreen) {
$scope.customFullscreen = (wantsFullScreen === true);
});
};
});
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
JAVASCRIPT:
$(document).on("click", "#button", function(){
var scope = angular.element($("#appCtrl")).scope();
scope.$apply(function(){
scope.showDialog();
scope.brokenLink = "Updated from JS";
});
});
在上面的小提琴中,我想将变量brokenLink中的值显示到对话框文本框中
最佳答案 您不应该使用jQuery来修改DOM.请改用Angular内置指令.在这种情况下ng-click.在你的代码中它将是这样的:
HTML:
<button id="button" ng-click="updateValue()">
Update value in Dialog
</button>
在控制器中:
$scope.updateValue = function() {
$scope.brokenLink = "Updated from JS";
}
编辑:要在DialogController中使用brokenLink值,请使用mdDialog locals,如下所示:
$mdDialog.show({
...
locals: { brokenLink: $scope.brokenLink }
...
});
function DialogController($scope, $mdDialog, brokenLink) {
$scope.brokenLink = brokenLink;
...
});
再次编辑:这是更新的JSFiddle:http://jsfiddle.net/hcpay1zm/172/