1

我可能只是在这里混淆自己。但我有一个结合变量和文本的观点。而且我需要将整个内容作为字符串存储在我的模型中。IE。

<h3>
  {{vars.color}} is my color: {{theme.color.black}};
</h3>

我希望能够将字符串保存到:

{{preference.string}} // as 'base is my color: #000'

显示文本没有问题。但我想保存整个字符串。(好像我可以添加 ng-model)到“h3”标签。但这不起作用。

我应该在函数或指令中这样做吗?

提前致谢...

4

2 回答 2

1

Generally it is considered bad to touch the DOM from a controller.

However, in your case I don't see other options and as you're only reading from the DOM and not manipulating it in any way it's not as bad.

Assuming you have the text rendered in a controller, you can use $element to gain access to the element and then fetch the text content. Again, this is a last resort and against the Angular philosophy.

var app = angular.module("myApp", [])
app.controller("HomeController", HomeController);

function HomeController($scope,$element) {
    $scope.vars = {};
    $scope.vars.color = "Black";
    $scope.theme = {color:{}};
    $scope.theme.color.black = "#000000";

    $scope.snap = function(){
        alert($element.find("h3").text()); // will alert the text
    }
}

Here is a working example

Alternatively, you can decouple this logic from a controller (and the used DOM) completely using $compile. This is a rather long example but it gives you a peek into Angular's way of doing things, this doesn't require an app.

var $inj = angular.injector(["ng"]); // get access to Angular's services
var template = "<h3>{{vars.color}} is my color: {{theme.color.black}}</h3>"

//now let's access the compilation service, and also a scope service and get a new scope.
var $compile = $inj.get("$compile");
var $scope = $inj.get("$rootScope").$new(true);

// put our stuff in this new scope
$scope.vars = {color:"White"};
$scope.theme = {color:{black:"#000000"}};

// add the template 
var ngTemplate = $compile(angular.element(template));
var result = ngTemplate($scope); 
$scope.$apply(); // tell angular to apply changes to the scope
console.log(result.text()); // now we have our rendered text.
// calling $destroy on the scope here is probably good ;)

here is a fiddle for that

However, are you sure what you're looking for is not partial views? What is the purpose of this?

于 2013-10-25T00:38:04.283 回答
0

我认为有指令嵌入不同的 html 内容是件好事。你可以做这样的事情。

<h3 show-data>
</h3>

指令:

 angular.module('myApp', [])
  .controller('Ctrl', function($scope) {
    $scope.vars.color = "base";
    $scope.theme.color.black = "#000";
  })
  .directive('showData', function() {
    return {
      template: '{{vars.color}} is my color: {{theme.color.black}}'
    };
  });

控制器的范围变化:

$scope.preference.string = $scope.vars.color + "is my color: " + $scope.theme.color.black;
于 2013-10-24T23:46:34.640 回答